带有链接列表的队列如何工作

时间:2020-09-15 23:46:30

标签: c# algorithm data-structures linked-list queue

有人可以解释一下enqueue方法的工作原理吗?

  • 我想知道重新分配后排后如何更新前排?

     public class Queue { 
     public QNode front, rear; 
    
     public Queue() 
     { 
         this.front = null;
         this.rear = null; 
     } 
    
     public void enqueue(int key) 
     {
         QNode temp = new QNode(key); 
    
         if (this.rear == null) { 
             this.rear = temp;
             this.front = temp; 
             return; 
         }
    
         this.rear.next = temp; 
    
         this.rear = temp;
     } 
    
    
     public void dequeue() 
     { 
         if (this.front == null) 
             return; 
    
         QNode temp = this.front; 
         this.front = this.front.next; 
    
         if (this.front == null) 
             this.rear = null; 
     } 
    

    }

1 个答案:

答案 0 :(得分:1)

首先,该方法使用给定的键创建一个新节点,然后检查后方是否为空(这实际上意味着队列为空)。如果队列为空,则由于它是列表中的唯一节点,因此将新节点的键设置为后方和前方。如果列表不为空,则将节点链接到后方(this.rear.next==temp)并将其更新为新的后方。

关于您有关前端的问题,在使用入队时不需要更新。 Enqueue将节点添加到列表的末尾,并将其更新为末尾。出队从前端移除节点并更新新的前端(原始前端之后的节点)。

相关问题