0
這是我用於實現單鏈表的完整Java源代碼。我看過很多教程,他們一直在討論如何在開始時插入節點。所以,我決定在我的代碼中添加一個方法insertAfterNode(int y)
,我可以在特定節點之後的節點內添加數據。在鏈表中的特定節點之後插入
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package datastructures;
/**
*
* @author Administrator
*/
public class Link {
int data;
Link next;
public Link(int d) {
this.data = d;
}
public void display() {
System.out.println(data);
}
public static class LinkedList {
Link first;
public void insertItemFirst(int x){
Link newLink = new Link(x);
newLink.next = first;
first = newLink;
}
public Link deleteFirst() {
Link temp = first;
first = first.next;
return temp;
}
public void displayList() {
Link current = first;
while (current != null) {
current.display();
current = current.next;
}
}
// START Of METHOD
public void insertAfterNode(int y) {
// Considering LinkedList is Sorted
Link newNode = new Link(y);
Link current = first;
while (current != null) {
while (current.data < y) {
current = current.next;
newNode.next = current;
current = newNode;
}
}
}
//END Of METHOD
}
public static void main(String[] args) {
LinkedList addelements = new LinkedList();
addelements.insertItemFirst(20);
addelements.insertItemFirst(30);
addelements.insertItemFirst(40);
addelements.insertItemFirst(50);
addelements.insertAfterNode(44);
addelements.displayList();
System.out.println("After Calling Deletion Method Once ");
addelements.deleteFirst();
addelements.displayList();
}
}
上面的代碼繼續在Netbeans中運行,我不得不停止構建退出它。我相信我的方法實現有問題。請讓我知道我的以下方法有什麼問題:
public void insertAfterNode(int y) {
// Considering LinkedList is Sorted
Link newNode = new Link(y);
Link current = first;
while (current != null) {
while (current.data < y) {
current = current.next;
newNode.next = current;
current = newNode;
}
}
}
如果沒有上述方法,代碼就會正常運行。
你的外部'while循環'永遠不會終止。除了最後輸入新節點之外,它不可能終止。你需要重新設計你的邏輯。 – 2015-03-13 09:19:59
在高層把這個問題分爲兩部分。 1.找出所需的節點 2.將給予節點之後一個新的節點 閱讀:[問題的理解節點的概念和鏈接列表(http://stackoverflow.com/questions/24895790/problems-understanding -concept-的節點和鏈接列表/ 24895863#24895863) – Braj 2015-03-13 10:47:21