Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Solution1:Iterative 依次比较 实时删除重复的
思路1_a:cur和prev相比较,若相同则delete cur;Note: 不应创建dummy从而从第一位开始,因为加入dummy的值可能影响重复,所以直接从第二位list开始。
思路1_b:cur和cur.next相比较
Time Complexity: O(N) Space Complexity: O(1)
Solution2:Iterative Two pointers "复写" (连接不重复的)
思路类似26题 http://www.jianshu.com/p/08a020a51fb3
Time Complexity: O(N) Space Complexity: O(1)
Solution3:Recursive 先序/后序 写法
思路3_a:递归。先序处理当前,再递归
思路3_b:递归。先递归,后序处理当前
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution1a Code:
class Solution1a {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return head;
// if(head == null || head.next == null) return head;
ListNode prev = head;
ListNode cur = head.next;
while(cur != null) {
ListNode next_save = cur.next; // for full delete
if(cur.val == prev.val) {
prev.next = cur.next;
cur.next = null; // for full delete
}
else {
prev = cur;
}
cur = next_save;
}
return head;
}
}
Solution1b Code:
class Solution1b {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return head;
ListNode cur = head;
while(cur.next != null) {
if(cur.val == cur.next.val) {
ListNode save_next = cur.next; // for fully deletion
cur.next = cur.next.next;
save_next.next = null; // for fully deletion
}
else {
cur = cur.next;
}
}
return head;
}
}
Solution2 Code:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next == null) return head;
ListNode new_cur = head;
ListNode cur = head.next;
while(cur != null) {
if(cur.val != new_cur.val) {
new_cur.next = cur;
new_cur = cur;
}
// ListNode save_next = cur.next; [for fully deletion]
// cur.next = null;
// cur = save_next;
cur = cur.next;
}
new_cur.next = null; //cut
return head;
}
}
Solution3a Code:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
if(head.next.val == head.val) { // if duplicated
head.next = head.next.next;
head = deleteDuplicates(head); //restart
}
else { // if not duplicated
head.next = deleteDuplicates(head.next); // move next
}
return head;
}
}
Solution3b Code:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
}