颠倒列表时我正在使用下面的代码,但它添加了最后一个元素两次。颠倒链表
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 ]
像这样的例子是最好的理解,如果你犯了一个小绘图和移动指针作为分配在程序中进行。你很快就会发现它出错的地方。 – Henry
有没有不使用java.util.List的原因? – Julisch
只需在head节点为空时将return语句添加到add方法中。 –