天天看點

删除連結清單中所有值為val的結點

題目:

删除連結清單中等于給定值 val 的所有結點。

思路:

(1)周遊連結清單,等于val的結點直接删除。(注意:當删除一個結點需要它的前驅結點)

(2)需要考慮如果頭結點的值為val該怎麼辦。

删除值相等的結點:

while(cur != null){
	if(cur.val == val){
		pre.next = cur.next;
	}else{
		pre = cur;
	}
	cur = cur.next;
}
           

考慮頭結點的值等于val的情況:

(1)Node一個絕對不等于val的假的頭結點,讓它指向連結清單。

Node newHead = newNode(-1);
newHead.next = head;
Node cur = newHead;
Node pre = null;

while(cur != null){
	if(cur.val == val){
		pre.next = cur.next;
	}else{
		pre = cur;
	}
	cur = cur.next;
}
return newHead.next;
           

完整程式:

https://github.com/WangWenQian12/Java_Practice/blob/master/JavaSE/IDEA/LinkedList/Review/RemoveAll/RemoveAll2/src/RemoveAll.java

(2)先處理頭結點的值等于val的情況。

if(head.val == val){
	head = head.next;
}

Node cur = head;
Node pre = null;

while(cur != null){
	if(cur.val == val){
		pre.next = cur.next;
	}else{
		pre = cur;
	}
	cur = cur.next;
}
return head;
           

完整程式:

https://github.com/WangWenQian12/Java_Practice/blob/master/JavaSE/IDEA/LinkedList/Review/RemoveAll/RemoveAll1/src/RemoveAll.java

(3)特殊處理

while(cur != null){
	if(cur.val == val){
		if(cur == head){
			head = cur.next;
		}else{
			pre.next = cur.next;
		}
	}else{
		pre = cur;
	}
	cur = cur.next;
}
return head;
           

完整程式:

https://github.com/WangWenQian12/Java_Practice/blob/master/JavaSE/IDEA/LinkedList/Review/RemoveAll/RemoveAll3/src/RemoveAll.java

繼續閱讀