LeetCode - Remove Duplicates from Sorted List
2013-12-26 21:42
447 查看
Remove Duplicates from Sorted List
2013.12.26 21:36
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
Solution:
Removing the duplicates from a list requires two pointers ptr1 and ptr2. With ptr1 pointing to current node, and ptr2 next to ptr1, the operation can be done in only one-pass. Please see the code below.
Time complexity is O(n), space complexity is O(1).
Accepted code:
2013.12.26 21:36
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.
Solution:
Removing the duplicates from a list requires two pointers ptr1 and ptr2. With ptr1 pointing to current node, and ptr2 next to ptr1, the operation can be done in only one-pass. Please see the code below.
Time complexity is O(n), space complexity is O(1).
Accepted code:
/** * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. if(head == nullptr){ return head; } ListNode *ptr1, *ptr2; ptr1 = head; ptr2 = head->next; while(ptr2 != nullptr){ if(ptr1->val == ptr2->val){ ptr1->next = ptr2->next; delete ptr2; ptr2 = ptr1->next; }else{ ptr1 = ptr1->next; ptr2 = ptr1->next; } } return head; } };
相关文章推荐