Remove Duplicates from Sorted List
LeetCode: Remove Duplicates from Sorted List
Problem:
Given a sorted linked list, delete all duplicates such that each element appear only once.
- Examples:
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
- Analysis:
Declare two pointers, A and B.
One of them, A, is to point at a dinstinct number starting node, the other, B, is to scan the linked list.
While the val of A isn't equal to the val of B, A.next = B, B scan the next node.
- Code - Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode prev = head;
ListNode ptr = head.next;
while (ptr != null) {
if (ptr.val != prev.val) {
prev.next = ptr;
prev = prev.next;
}
ptr = ptr.next;
}
prev.next = null;
return head;
}
}
- Code - C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL) {
return NULL;
}
ListNode* prev = head;
ListNode* ptr = head->next;
while (ptr != NULL) {
if (ptr->val != prev->val) {
prev->next = ptr;
prev = prev->next;
}
ptr = ptr->next;
}
prev->next = NULL;
return head;
}
};
- Code - 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:
return None
prev, ptr = head, head.next
while ptr != None:
if ptr.val != prev.val:
prev.next = ptr
prev = prev.next
ptr = ptr.next
prev.next = None
return head
- Code - C:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == 0) {
return 0;
}
struct ListNode* prev = head;
struct ListNode* ptr = head->next;
while (ptr != 0) {
if (ptr->val != prev->val) {
prev->next = ptr;
prev = prev->next;
}
ptr = ptr->next;
}
prev->next = 0;
return head;
}
Time Complexity: O(N), N is the length of listedlist
Space Complexity: O(1)