打印firstnode
地址后,会打印last node
地址,以便我想显示我的地址
Linked List
所以我该怎么做?
请提供有效的解决方案
public class LLink {
public Link first, last, tmp;
public void add(int data) {
Link newLink = new Link(data);
if (first == null) {
first = newLink;
System.out.println(first.data);
System.out.println(newLink);
} else {
first.next = newLink;
// first=newLink;
System.out.println(newLink.data);
// newLink = newLink.next;
// newLink.next=newLink;
last = newLink;
}
// newLink.next=first;//it copies the address of old first
// last=newLink;
System.out.println("end");
System.out.println(last);
}
public void delete() {
Link tmp = first;
first = first.next;
System.out.println(first.data);
}
public void display() {
System.out.println("display");
Link e = first;
while (e != null) {
System.out.println(e.data);
System.out.println(e);
System.out.println("first-next" + first.next);
System.out.println(e.next);
e = e.next;
}
}
class Link {
public int data;
public Link next;
public Link(int data) {
this.data = data;
}
}
}
答案 0 :(得分:1)
添加功能存在问题,而不是显示功能。
public void add(int data) {
Link newLink = new Link(data);
if (first == null) {
first = newLink;
System.out.println(first.data);
System.out.println(newLink);
} else {
first.next = newLink; // <-- This is wrong
// first=newLink;
System.out.println(newLink.data);
// newLink = newLink.next;
// newLink.next=newLink;
last = newLink;
}
// newLink.next=first;//it copies the address of old first
// last=newLink;
System.out.println("end");
System.out.println(last);
}
添加到链接列表时,应添加到最后一个节点,而不是从第一个节点更改下一个指针。您已经有效地创建了一个双节点列表,每次添加节点时都会更改最后一个节点。
相反,你应该有类似的东西:
public void add(int data) {
Link newLink = new Link(data);
if (first == null) {
first = last = newLink;
} else {
last.next = newLink; // First set the next pointer of the last node to the new node
last = newLink; // Once the pointer is set, now set last node properly
}
}