[英]Implementing Doubly Linked List from scratch, error in remove() method
我試圖學習在java中實現Doubly Linked List作為練習。 但我被困在remove()
方法。
列表的內容是,
1 2 3 4
當我嘗試刪除不存在的元素時。它line no. 21
處顯示NullPointerException
line no. 21
line no. 21
而not found
打印。
我看到的其他代碼有點復雜,與我正在做的不同。 方法是,
void remove(int data){
Node n = head;
if(head==null)
System.out.println("Not Found");
else if(head.d==data){
if(head==tail){
head=null;
tail=null;
}
else{
head=head.next;
head.prev=null;
}
}
else{
while(n!=null && n.d==data){
n=n.next;
}
if(n==tail){
tail=tail.prev;
tail.next=null;
}
else if(n!=null){
n.prev.next=n.next;
n.next.prev=n.prev;
}
if(n==null)
System.out.println("Not Found");
}
}
所以我的問題是,我完全錯了嗎? 或者問題是什么? 請原諒我,如果它太愚蠢了。
問題在於搜索邏輯。 在while循環條件中,“nd == data”不正確。 它應該是“nd!= data”即
while(n!= null && nd == data){
N = n.next;
}
應該:
...
while(n!=null && n.d != data){
n=n.next;
}
這是一個更清潔的實現:
public void remove(int data) { // Head is not required in param, should be field variable
Node ptr = head;
while(ptr!=null && ptr.data != data) // search for the node
{
ptr = ptr.next;
}
if(ptr == null) {
System.out.println("Not Found");
return;
}
if(ptr.prev == null) {// match found with first node
head = ptr.next;
}
else{
ptr.prev.next = ptr.next;
}
if(ptr.next == null){// match found with last node
tail = ptr.prev;
}
else{
ptr.next.prev = ptr.prev;
}
}
void remove(Node head, int value) {
if (head == null) {
System.out.println("Not Found");
} else if (value == head.d) {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
}
} else {
Node n = head.next;
while (n != null && value != n.d) {
n = n.next;
}
if (n == tail) {
tail.next = null;
tail = tail.prev;
} else if (n != null) {
n.prev.next = n.next;
n.next.prev = n.prev;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.