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的所有節點。
樣例:
給出鏈表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回刪除3之后的鏈表:1->2->4->5。
** 分析: **
1.首先判斷head是不是空,為空就直接返回null
2.然后從head.next開始循環遍歷,刪除相等于val的元素
3.最后判斷head是否和val相等,若相等,head = head.next
(這里最后判斷head是有原因的,因為head只是一個節點,只要判斷一次,如果最先判斷head就比較麻煩,因為如果等于val,head就要發生變化)
這里也體現出為什么設計鏈表的時候要空出一個頭結點
** 代碼 **:
/**
* 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;
//操作鏈表時的技巧,為了方便返回結果,我們新建一個dummy節點作為一個頭結點
ListNode dummy = new ListNode(0);
dummy.next = head;
//刪除鏈表時的操作,最好加一個頭結點,這樣刪除的操作就是:head.next = head.next.next
head = dummy;
//開始循環鏈表,結束的條件是到達最后一個節點,因為有一個頭結點的存在,所以是head.next != null
while(head.next != null) {
//如果head.next節點等于val,就是要被刪除的節點
if(head.next.val == val)
head.next = head.next.next;
//否則繼續判斷下一個節點
else
head = head.next;
}
return dummy.next;
}
}
Paste_Image.png
在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;
}
思路比較新穎,但原理很簡單,遞歸調用,如果當前節點等于val就刪除,但是效率較低,但不失為拓展思路的好方法,或許鏈表的結構也利于使用遞歸?
Paste_Image.png