我正在创建一个单独链接的循环列表,我似乎不明白为什么它不起作用。这是我的代码。有人会帮助我并指出我做错了什么吗?我能够添加第一个节点,但我不明白如何添加第二个节点。有人可以告诉我如何改变它。我认为我的名单无休止地遍历这就是原因。
public class CircularList <E> {
private Node<E> head;
private class Node <E>
{
E data;
Node <E> next;
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
public Node(E data)
{
this.data = data;
this.next = null;
}
}//node
public CircularList()
{
head = null;
}
public void add(E data)
{
Node <E> temp = new Node <E> (data);
if(head==null)
{
head=temp;
temp.next=temp;
System.out.println(head.next.data);
}
else
{
Node<E> temp2 = head.next;
while(temp2!=head)
{
if(temp2.next==head)
{
temp2.next=temp;
temp.next=head;
}
temp2=temp2.next;
}
}
}
答案 0 :(得分:0)
如果你想让你的单链表循环,那么有一个尾巴是个好主意,那么你的代码就可以是(伪代码)
function addElement(data){
Node n = new Node(data)
if(list.isEmpty() ){
head = n
tail = n
n.setNext(n)
} else {
n.setNext(head)
tail.setNext(n)
head = n
}
}
答案 1 :(得分:0)
用此更新您的其他部分;
Node<E> temp2 = head;
while(temp2.next != head)
{
temp2=temp2.next;
}
temp2.next=temp;
temp.next=head;