I have to implement a queue using a linked list while doing enqueue I have to sort the queue in descending order and print it, dequeue is normal
I called the sort function every time I do enqueue, I get some error in the sort function error: [1]: https://i.stack.imgur.com/qVwri.png
class Queue:
def __init__(self):
self.front = self.rear = None
class Node:
def __init__(self, data):
self.data = data # Data part of the node
self.next = None # Next reference of the node
def print(self):
curr = self.front
string = ''
while curr:
string = '|' str(curr.data) '|'
curr = curr.next
print(string)
def is_Empty(self):
return self.front == None
def sort(self):
curr = self.front
while curr.next:
if curr.data < curr.next.data:
temp = curr.next
curr.next = curr
curr = temp
curr = curr.next
def Enqueue(self, item):
temp = Node(item)
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
def Dequeue(self):
if self.is_Empty():
return("The Queue is empty!")
temp = self.front
self.front = temp.next
if (self.front == None):
self.rear = None
return self.rear
if __name__ == '__main__':
q = Queue()
while (True):
choice = int(input("1. Enqueue\n2. Dequeue\n3. Exit\n"))
if (choice == 1):
data_ll = int(input("Please enter the data: "))
q.Enqueue(data_ll)
q.sort()
q.print()
elif (choice == 2):
q.Dequeue()
q.print()
CodePudding user response:
The first error was in creating a node in Enqueue function. The inner class function should be called as self.Node and the other thing was sorting function doesn't sort.
Given below is the fixed code
class Queue:
class Node:
def __init__(self, data):
self.data = data # Data part of the node
self.next = None # Next reference of the node
def __init__(self):
self.front = self.rear = None
def print(self):
curr = self.front
string = ''
while curr:
string = '|' str(curr.data) '|'
curr = curr.next
print(string)
def is_Empty(self):
return self.front == None
def get_size(self):
temp = self.front
count = 0
while (temp):
count = 1
temp = temp.next
return count
def sort(self):
# print("[",curr.data,"]")
count=self.get_size()
while(count):
curr = self.front
while (curr and curr.next):
if curr.data > curr.next.data:
temp=curr.data
curr.data=curr.next.data
curr.next.data=temp
curr = curr.next
count-=1
def Enqueue(self, item):
temp = self.Node(item)
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
def Dequeue(self):
if self.is_Empty():
return("The Queue is empty!")
temp = self.front
self.front = temp.next
if (self.front == None):
self.rear = None
return self.rear
if __name__ == '__main__':
q = Queue()
while (True):
choice = int(input("1. Enqueue\n2. Dequeue\n3. Exit\n"))
if (choice == 1):
data_ll = int(input("Please enter the data: "))
q.Enqueue(data_ll)
q.sort()
q.print()
elif (choice == 2):
q.Dequeue()
q.print()
```