Reverse First K Elements

COSC 2306 - Stacks & Queues Algorithm Visualizer

Visual Workspace

Input Elements (to be processed)
mystack (LIFO)
myq (FIFO)
all_elements [ Result ]

Setup & Controls

Algorithm Concept

  • The first K elements are sent to a Stack, which reverses their order when popped.
  • The remaining elements are sent to a Queue, maintaining their original order when dequeued.
  • Finally, emptying the Stack followed by the Queue pieces them back together!

Program Source Code

This demonstrates exactly how the Python assignment functions, bringing together standard operations like push(), pop(), enqueue(), and dequeue().

View firstKSQ() in Python
def firstKSQ():
    num_elements = int(input('How many elements? '))
    k = int(input('How many first elements to be reversed? '))

    mystack = Stack()
    myq = Queue()
    count = 0
    
    # Phase 1: Distribute elements to Stack and Queue
    for i in range(num_elements):
        val = int(input('Please enter element: '))
        if count < k:
            mystack.push(val)
        else:
            myq.enqueue(val)
        count += 1

    # Phase 2: Retrieve elements into final list
    all_elements = []
    while not mystack.isEmpty():
        all_elements.append(mystack.pop())
        
    while not myq.isEmpty():
        all_elements.append(myq.dequeue())