我試圖從我單鏈表中刪除最後一個節點。但是我仍然無法解決代碼中的這個錯誤。我的deleteFromEnd
方法不會刪除最後一個節點。在調用delete方法後,它仍然顯示我想要刪除的節點。列表的其餘部分將被刪除,但最後一個節點本身不會被刪除。你能告訴我我錯過了什麼,或者錯誤在哪裏?無法刪除鏈表中的最後一個節點
的LinkedList:
package lab5;
public class LinkedList {
public static void main(String argsp[]) {
List ob = new List();
ob.addAtStart("y", 6);
ob.addAtStart("w", 4);
ob.addAtStart("z", 3);
ob.addAtEnd("a", 3);
ob.addAtEnd("b", 4);
ob.addAtEnd("c", 5);
/*
* ob.display(); System.out.println("Deleted first one");
* ob.deleteFromStart();
*/
ob.display();
System.out.println("Deleted End one");
ob.deleteFromEnd();
ob.display();
}
}
列表:
package lab5;
public class List {
Node head;
public List() {
head = null;
}
public List(Node e) {
head = e;
}
Node oldfirst = null;
Node lasthead = null;
public void addAtStart(String name, int age) {
Node newObject = new Node(name, age);
newObject.next = head;
if (oldfirst == null) {
oldfirst = newObject;
}
head = newObject;
lasthead = head;
}
public void display() {
Node store = head;
while (store != null) {
store.display();
store = store.next;
System.out.println();
}
}
public void addAtEnd(String name, int age) {
Node atEndValue = new Node(name, age);
oldfirst.next = atEndValue;
oldfirst = atEndValue;
}
public void deleteFromStart() {
if (head.next != null) {
head = head.next;
}
}
public void deleteFromEnd() {
Node start = head;
Node prev = null;
while (head != null) {
prev = head;
head = head.next;
}
prev.next = null;
head = prev;
}
public Node search(String name) {
return head;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return (head.toString()).length();
}
}
節點:
package lab5;
public class Node {
String name;
int age;
Node next;
public Node() {
name = "Abc";
age = 10;
next = null;
}
public Node(String name, int age) {
this.name = name;
this.age = age;
next = null;
}
public void display() {
System.out.println("Name: " + name + " Age: " + age);
}
}
@nbrooks現在我問新的問題。 – Shahzad
'head = head.next;'有什麼意義? – shmosel
你正在遍歷使用'head'而不是使用本地變量'start'。 – shmosel