2016-07-14 135 views
0

我想刪除LinkedList中的最後一個節點。 對於輸入:1,2,3 輸出應該是:1,2實現刪除鏈表最後一個節點的方法

我能夠刪除節點,但是有沒有更好/更有效的方法?

請檢查removeLastNode()方法。

public class MyLinkedList { 

Node head; 
Node tail; 

public void add(int number){ 

    Node node=new Node(); 
    node.setNumber(number); 

    if(head==null){ 
     head=node; 
     tail=node; 
    } 
    else{ 
     tail.next=node; 
     tail=node;   
    } 

} 



public void removeLastNode(){ 
    Node temp=head; 
    Node head1=null; 
    Node tail1=null; 


    while(temp.next!=null){ 

     Node node=new Node(); 
     node.number=temp.number; 
     if(head1==null){ 
      head1=node; 
      tail1=node; 
     } 
     else{ 
      tail1.next=node; 
      tail1=node;   
     } 
     if(temp.next.next==null){    
      temp.next=null; 
      break; 
     } 

     temp=temp.next; 

    } 
    head=head1; 


} 


@Override 
public String toString(){ 
    while(head!=null){ 
     System.out.print(head.getNumber()+" "); 
     head=head.getNext(); 
    } 
    return ""; 
} 

public static void main(String ar[]){ 

    MyLinkedList list=new MyLinkedList(); 
    list.add(1); 
    list.add(2); 
    list.add(3); 
    list.removeLastNode(); 

    System.out.println(list); 
} 




public class Node{ 

    Node next; 
    int number; 
    public Node getNext() { 
     return next; 
    } 
    public void setNext(Node next) { 
     this.next = next; 
    } 
    public int getNumber() { 
     return number; 
    } 
    public void setNumber(int number) { 
     this.number = number; 
    } 


} 

}

+0

您可以使用其中每個節點存儲的地址到一個和下一個節點雙向鏈表 – Slimu

+0

注意'Java's類'LinkedList'由**默認情況下實現了'雙聯list' * *,它不是一個普通的'鏈表'!因此,你已經可以很好地使用Java的'LinkedList'了。或者,如果您需要自行實施,則可以查看如何在此處執行此操作。 – Zabuza

回答

0

使用tail是最後一個節點。

public void removeLastNode() { 
    if (head == null) { 
     throw new IllegalStateException(); 
    } 
    if (head == tail) { 
     head = null; 
     tail = null; 
    } else { 
     Node current = head; 
     while (current.next != tail) { 
      current = current.next; 
     } 
     current.next = null; 
     tail = current; 
    } 
} 
+0

謝謝你..環Eggen – Premkumar

1

添加Node previous屬性的NodeNode last到鏈表得到DoubleLinkedList。

然後,你可以這樣做

Node temp = List.getLast().getPrevious(); //returns the second last item 
List.removeLast(); //sets the last item to null 
List.setLast(temp); //sets the last item to the second last item 
List.getLast().setNext(null);