2016-04-27 216 views
-1

颠倒列表时我正在使用下面的代码,但它添加了最后一个元素两次。颠倒链表

public void reverse() 
    { 
     Node current,previous,next; 
     current=head; 
     previous=null; 
     while(current!=null) 
     { 
      next=current.getNext(); 
      current.setNext(previous); 
      previous=current; 
      current=next; 
     } 
     head=previous; 
    } 

节点类以下

public class Node 
{ 
    private Node next; 
    private String data; 

    public Node(String dataValue) { 
     next = null; 
     data = dataValue; 
    } 

    public Node getNext() { 
     return next; 
    } 

    public void setNext(Node next) { 
     this.next = next; 
    } 

    public String getData() { 
     return data; 
    } 

    public void setData(String data) { 
     this.data = data; 
    } 
} 

我按照

public void add(String data) 
    { 
     if(head==null) 
     { 
      head=new Node(data); 
     } 
     Node temp=new Node(data); 
     Node current=head; 
     if(current!=null) 
     { 
      while(current.getNext()!=null) 
      { 
       current=current.getNext(); 
      } 
      current.setNext(temp); 
     } 
    } 

倒车列表我得到的输出后添加在列表中的数据是继

原始列表:[1] [2] [3] [4] [5] 逆向列表:[4] [3] [2] [1] [1 ]

+2

像这样的例子是最好的理解,如果你犯了一个小绘图和移动指针作为分配在程序中进行。你很快就会发现它出错的地方。 – Henry

+0

有没有不使用java.util.List的原因? – Julisch

+0

只需在head节点为空时将return语句添加到add方法中。 –

回答

1

你的问题是在add方法时,有no head到目前为止,你需要添加一个return声明,以避免将自身添加为next node,为下一个:

public void add(String data) 
{ 
    if(head==null) 
    { 
     head=new Node(data); 
     // Exit of the method to prevent adding the head as next element 
     // of the head 
     return; 
    } 
    ... 
} 

有了这个简单的变化,如果我做:

// Create the list 
MyList list = new MyList(); 
list.add("1"); 
list.add("2"); 
list.add("3"); 
list.add("4"); 
list.add("5"); 

// Print the list content 
current = list.head; 
while(current != null){ 
    System.out.println(current.getData()); 
    current = current.getNext(); 
} 

// Inverse the list 
list.reverse(); 
System.out.println("****"); 
// Print again the list content 
current = list.head; 
while(current != null){ 
    System.out.println(current.getData()); 
    current = current.getNext(); 
} 

输出:

1 
2 
3 
4 
5 
**** 
5 
4 
3 
2 
1 
0

填充列表时,头部设置为[1],然后在此头部后面插入节点[1]。 所以你总是有你的列表的第一个元素两次。

你最好使用java.list.LinkedList,你可以用Node

List<Node> yourList = new LinkedList<Node>(); 
yourList.add(new Node(1)); 
yourList.add(new Node(2)); 

填补然后,您可以扭转你的列表,只需运行:

Collections.reverse(yourList); 
+0

这个问题显然是一个编程练习,我非常怀疑这将成为解决方案。 – Henry