Search code examples
pythonrecursionlinked-listqueue

Recursive reversal of linked list implementation of queue


I am learning queues and completed with the linked list implementation of queue and Now my task was to recursively reverse the queue . So I tried by popping the first element and the calling the recursive function until the queue becomes empty and the calling the push/enqueue operation to push back the element back to the queue . Where am I going Wrong?

class Node:
    def __init__(self,data):
        self.data=data
        self.next=None

class Queue_LL:
    def __init__(self):
        self.head=None
        self.tail=None
        self.count=0

    def enqueue(self,item):
        temp=Node(item)
        if self.tail==None:
            self.head=temp
            self.tail=temp
            self.count += 1
        else:
            self.tail.next=temp
            self.tail=temp
            self.count+=1

    def dequeue(self):
        if not self.head:
            return None
        else:
            dequeue_element=self.head.data
            self.head=self.head.next
            if self.head==None:#we reached end of queue
                self.tail=None
            self.count-=1
            return dequeue_element

    def getFront(self):
        if not self.head:
            return
        else:
            return self.head.data

    def getRear(self):
        if not self.head:
            return
        else:
            return self.tail.data

    def size(self):
        return self.count

    def isEmpty(self):
        return self.count==0

def reverse(queue):
    if not queue:
        temp=queue.dequeue()
        reverse(queue)
        queue.enqueue(temp)


#driver code

q=Queue_LL()
q.enqueue(20)
q.enqueue(30)
q.enqueue(40)
q.enqueue(50)

print(q.getFront())
print(q.getRear())
print(q.size())
print(q.isEmpty())

#reverse queue

reverse(q)
print(q.getFront())
print(q.getRear())
print(q.size())
print(q.isEmpty())

Is the recursion function wrong ? Beccause the ouput expecting is 50 , 20 , 4 , False


Solution

  • In the reverse method, the condition is not correct because if not queue: will always be false. Here's the corrected version of the reverse method:

    def reverse(queue):
        if not queue.isEmpty():
            temp=queue.dequeue() 
            reverse(queue)
            queue.enqueue(temp)