[Leetcode]Remove Linked List Elements
阿新 • • 發佈:2019-01-03
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
分析:
1. 對於連結串列,在刪除當前節點時,需要知道當前節點的父節點。
2. 對於非頭節點,刪除操作很方便,對於頭節點需要額外的操作,為了在遍歷的過程中,保持刪除操作的一致性和避免區分頭節點和非頭節點,有兩種方法來避免這種麻煩:
①可以為連結串列設定輔助頭節點(即在原來連結串列前插入頭節點),這樣對具有輔助頭節點的連結串列,在遍歷時就不存在區分頭節點和非頭節點的問題。
The key to solve this problem is using a helper node to track the head of the list.
②從頭節點的下一個節點開始遍歷查詢刪除,遍歷完成後再處理頭節點。
程式一
public class Solution { public ListNode removeElements(ListNode head, int val) { ListNode helpHead = new ListNode(0); helpHead.next = head; ListNode cursor = helpHead; while (cursor.next != null) { if (cursor.next.val == val) { cursor.next = cursor.next.next; } else { cursor = cursor.next; } } return helpHead.next; } }
程式二
public ListNode removeElements(ListNode head, int val) { if (head == null) return null; ListNode pointer = head; while (pointer.next != null) { if (pointer.next.val == val) pointer.next = pointer.next.next; else pointer = pointer.next; } return head.val == val ? head.next : head; }