【问题标题】:Queue Implementation Using linkedlist使用链表实现队列
【发布时间】:2014-09-21 04:45:59
【问题描述】:

this 队列实现示例中,我无法理解类节点内的内容,即下一个节点。它是我们当前所在的同一个 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;
     }
   }
   }

【问题讨论】:

    标签: java linked-list queue implementation


    【解决方案1】:

    它通过将元素的指针移动到队列中的下一个节点来删除元素

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多