3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
在 push 方法的 else 語句中有一個(gè)不必要的 while 循環(huán)。
而(溫度!=空)
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貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
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貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
while 循環(huán)是導(dǎo)致無限循環(huán)的原因。tmp!=null由于 tmp 保持原樣,因此條件不會變?yōu)榧?。它不是穿越。第二個(gè)函數(shù)的情況也是如此,其中 head 永遠(yuǎn)不會向前遍歷,因此如果它不為空,它將保持不為空并且循環(huán)不會結(jié)束。
這將工作 -
在你的 push() 函數(shù)中 -
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 在插入函數(shù)中通常沒有返回值,因?yàn)槲覀冎皇菍⒁恍?shù)據(jù)插入到數(shù)據(jù)結(jié)構(gòu)中。我們最多可能需要插入是否成功。
添加回答
舉報(bào)