2014-09-21 2 views
0

В примере this примера реализации очереди я не могу понять, что находится внутри класса Node, т. Е. Следующий узел. это тот же объект класса 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

Он удаляет элемент, перемещая ее указатель на следующий узел в очереди

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 
} 
Смежные вопросы