Remove all elements from a linked list of integers that have value val.
Example*****Given:* 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6Return: 1 --> 2 --> 3 --> 4 --> 5
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
描述:
刪除鏈表中等于給定值val的所有節(jié)點。
樣例:
給出鏈表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回刪除3之后的鏈表:1->2->4->5。
** 分析: **
1.首先判斷head是不是空,為空就直接返回null
2.然后從head.next開始循環(huán)遍歷,刪除相等于val的元素
3.最后判斷head是否和val相等蟹地,若相等姑子,head = head.next
(這里最后判斷head是有原因的鸠蚪,因為head只是一個節(jié)點重慢,只要判斷一次,如果最先判斷head就比較麻煩逊躁,因為如果等于val似踱,head就要發(fā)生變化)
這里也體現(xiàn)出為什么設(shè)計鏈表的時候要空出一個頭結(jié)點
** 代碼 **:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
//邊界條件判斷,如果head為null,則直接返回null
if(head == null)
return null;
//操作鏈表時的技巧稽煤,為了方便返回結(jié)果核芽,我們新建一個dummy節(jié)點作為一個頭結(jié)點
ListNode dummy = new ListNode(0);
dummy.next = head;
//刪除鏈表時的操作,最好加一個頭結(jié)點酵熙,這樣刪除的操作就是:head.next = head.next.next
head = dummy;
//開始循環(huán)鏈表轧简,結(jié)束的條件是到達(dá)最后一個節(jié)點,因為有一個頭結(jié)點的存在匾二,所以是head.next != null
while(head.next != null) {
//如果head.next節(jié)點等于val哮独,就是要被刪除的節(jié)點
if(head.next.val == val)
head.next = head.next.next;
//否則繼續(xù)判斷下一個節(jié)點
else
head = head.next;
}
return dummy.next;
}
}
在leetcode的討論中,看到一個特別的方法察藐,三行遞歸代碼解決這個問題:
首先我們先看代碼:
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
思路比較新穎皮璧,但原理很簡單,遞歸調(diào)用分飞,如果當(dāng)前節(jié)點等于val就刪除悴务,但是效率較低,但不失為拓展思路的好方法譬猫,或許鏈表的結(jié)構(gòu)也利于使用遞歸讯檐?