LeetCode, leetcodeoj
Link: Remove Duplicates from Sorted List II
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-> 5, return 1-> 2-> 5.
Given 1-> 1-> 1-> 2-> 3, return 2-> 3.
The requirement for this question is to delete nodes with duplicate numbers in the ordered linked list, leaving no duplicate nodes.
This is also the first question II, which is an extension of Remove Duplicates from Sorted List. In fact, both questions are similar, and basic linked List operations.
The idea is to find duplicate elements and delete them. If the numbers of the two consecutive nodes are the same, the system checks and deletes the repeated elements. However, you still need to delete the duplicate nodes because duplicate nodes are not required to be retained.
Time Complexity: O (n)
Space complexity: O (1)
1 class Solution 2 { 3 public: 4 ListNode *deleteDuplicates(ListNode *head) 5 { 6 ListNode *h = new ListNode(0), *p = h; 7 h -> next = head; 8 9 while(p -> next != NULL)10 {11 if(p -> next -> next != NULL && 12 p -> next -> val == p -> next -> next -> val)13 {14 while(p -> next -> next != NULL && 15 p -> next -> val == p -> next -> next -> val)16 p -> next = p -> next -> next;17 p -> next = p -> next -> next;18 }19 else20 p = p -> next;21 }22 23 return h -> next;24 }25 };
Reprinted please note the Source: LeetCode --- 82. Remove Duplicates from Sorted List II