当反转列表时,我使用以下代码,但它是两次添加最后一个元素。
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]
答案 0 :(得分: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
答案 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);