3 回答
TA贡献1836条经验 获得超4个赞
在 push 方法的 else 语句中有一个不必要的 while 循环。
而(温度!=空)
public Node push(int data){
Node newNode = new Node(data);
if(head == null){
newNode.next = head;
head = newNode;
}
else{
newNode.next = head.next;
head.next = new Node(data);
}
return head;
}
TA贡献1847条经验 获得超11个赞
public final class LinkedList {
private Node head;
// method name should be clear
public void addHead(int data) {
Node node = new Node(data);
if (!isEmpty())
updateLinksBeforeInsert(node, head);
head = node;
}
public void addTail(int data) {
Node node = new Node(data);
if (isEmpty())
head = node;
else
updateLinksBeforeInsert(findLastNode(), node);
}
public boolean isEmpty() {
return head == null;
}
// The last node is the node with 'next == null'
private Node findLastNode() {
Node node = head;
while (node.next != null)
node = node.next;
return node;
}
// Before insert both 'prev' and 'next' links should be correctly updated
private static void updateLinksBeforeInsert(Node prev, Node next) {
prev.next = next;
next.prev = prev;
}
// Accept a stream is more flexible than simple System.out
public void print(PrintStream out) {
Node node = head;
while (node != null) {
// print '-->' only after the first element
if (node != head)
out.print("-->");
out.print(node.data);
node = node.next;
}
}
// Node should not be visible outside LinkedList
private static final class Node {
final int data;
Node next;
Node prev;
private Node(int data) {
this.data = data;
}
}
TA贡献1789条经验 获得超8个赞
while 循环是导致无限循环的原因。tmp!=null由于 tmp 保持原样,因此条件不会变为假。它不是穿越。第二个函数的情况也是如此,其中 head 永远不会向前遍历,因此如果它不为空,它将保持不为空并且循环不会结束。
这将工作 -
在你的 push() 函数中 -
else{
Node node = new Node(data);
node.next = head;
head.prev = node; // taking into account that it is a dll
this.head = node;
return node;
}
还有你的 insertAtEnd(int data) -
public Node insertAtEnd(int data){
Node tmp = this.head;
while(tmp.next!=null){
tmp = tmp.next;
}
tmp.next = new Node(data);
tmp.next.prev = tmp; // taking into account that it is a dll
return tmp.next;
}
PS 在插入函数中通常没有返回值,因为我们只是将一些数据插入到数据结构中。我们最多可能需要插入是否成功。
添加回答
举报