Lintcode: 112 · Remove Duplicates from Sorted List - LintCodeeasy
# Description
# Given a sorted linked list, delete all duplicates such that each element appear only once.
Linked list length <= 30000<=30000
Example
Example 1:
Input:
linked list = null
Output:
null
Explanation:
Empty linked list returns null
Example 2:
Input:
linked list = 1->1->2->null
Output:
1->2->null
Explanation:
Delete duplicate 1
Example 3:
Input:
linked list = 1->1->2->3->3->null
Output:
1->2->3->null
Explanation:
Delete duplicate 1 and 3
# 解題思路
這題很直觀的就是如果我當前的 node 和下一個 node 一樣的話,那我就指向下下一個(把它跳過的意思)
public ListNode deleteDuplicates(ListNode head) { | |
if(head == null) return null; | |
ListNode node = head; | |
while (head.next != null){ | |
if(node.val == node.next.val){ | |
node.next = node.next.next; | |
} else { | |
node = node.next; | |
} | |
} | |
return head; | |
} |
# 快慢指針
這種有序的鏈表,可以讓 fast
快指針先走前面,慢指針 slow
走後面,如果 fast
走到重復的節點,就讓 slow
跳過,走到不重複時,讓 slow
走一步,跟上面解法差不多。
public ListNode deleteDuplicates(ListNode head) { | |
if(head == null) return null; | |
ListNode slow = head, fast = head; | |
while (fast != null){ | |
if(fast.val != slow.val){ | |
// 讓 slow 等於現在的 fast | |
//e.g. nums[slow] == nums[fast] | |
slow.next = fast; | |
slow = slow.next; // 不重復時可以往前走 | |
} | |
fast = fast.next; | |
} | |
return head; | |
} |