简体   繁体   English

使用链表实现队列

[英]Queue Implementation Using linkedlist

In this queue implementation example, i am not able to understand what is inside the class Node ie Node next. 队列实现示例中,我无法理解类Node(即下一个Node)中的内容。 is it the same Node class object that we are currently in or some other class. 是我们当前所在的Node类对象还是其他类。 how is deletefirst() removing the first element? deletefirst()如何删除第一个元素?

    import java.io.*;
    class Node
    {
       public int data;
       public Node next;
       public Node(int x)
       {
         data=x;
       }
       public void displayNode()
       {
         System.out.print(data+"  ");
       }
    }
    class LinkList
    {
      

 private Node first;
   private Node last;
   public LinkList()
   {
     first=null;
     last=null;
   }
   public void insertLast(int x)
   {
     Node newNode=new Node(x);
     newNode.next=null;
     if(isEmpty())
       first=newNode;
     else
       last.next=newNode;
     last=newNode;
   }
   public int deleteFirst()
   {
     int t=first.data;
     if(first.next==null)
       last=null;
     first=first.next;
     return t;
   }
   public int peekFirst()
   {
     return(first.data);
   }
   public boolean isEmpty()
   {
     return(first==null);
   }
   public void displayList()
   {
     Node current=first;
     while(current!=null)
     {
       current.displayNode();
       current=current.next;
     }
   }
   }

It removes the element by moving its pointer to the next node in the Queue 它通过将其指针移动到队列中的下一个节点来删除该元素

public int deleteFirst()
{
  int t=first.data; // Gets data from first Node.
  if(first.next==null) // Checks if next element is null. If true. Queue is empty so last element is null
    last=null;
  first=first.next; // Sets first to the next Node. <== This is where your magic happens.
  return t; // Returns the removed item from your Queue
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM