Leetcode[81, 82] Remove Duplicates from Sorted List
06 Nov 2015###Task1 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.
###Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
cur = head
while head.next:
if head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
return cur
###Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
//edge cases
if (head == null) {
return null;
}
ListNode dum = head;
while (head.next != null) {
if (head.val == head.next.val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return dum;
}
}
###Task2 Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.
###Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
dummy = ListNode(0)
dummy.next = head
head = dummy
while head.next and head.next.next:
if head.next.val == head.next.next.val:
cur = head.next.val
while head.next and head.next.val == cur:
head.next = head.next.next
else:
head = head.next
return dummy.next
###Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
//edge
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head.next != null && head.next.next != null) {
if (head.next.val == head.next.next.val) {
int value = head.next.val;
while (head.next != null && head.next.val == value) {
head.next = head.next.next;
}
} else {
head = head.next;
}
}
return dummy.next;
}
}
###Points
- if dup –> change next –> head.next = …
- if not –> change head –> head = …
- Original head may change –> dummy