在this队列实现示例中,我无法理解Node类中的内容,即Node next。它是我们当前所在的Node类对象还是其他类。 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;
}
}
}
答案 0 :(得分:0)
它通过将其指针移动到队列中的下一个节点
来删除该元素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
}