Title Link: Remove duplicates from Sorted List II
Given a sorted linked list, delete all nodes that has 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.
The requirement of this problem is to delete the nodes with duplicate numbers in the ordered list, leaving no duplicate nodes.
Is the first appearance of the second topic, is the extension of the Remove duplicates from Sorted list, in fact, these two questions are similar, the basis of the list operation.
The idea is to find duplicate elements and delete them. If the number of two consecutive nodes is the same, then the loop detects and removes the duplicate elements, but finally the duplicate node needs to be deleted because the duplicate nodes are not required to be preserved.
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {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)Ten { One if(P - Next - Next != NULL && A P - Next - Val == P - Next - Next - Val) - { - while(P - Next - Next != NULL && the P - Next - Val == P - Next - Next - Val) - P - Next = P - Next - Next; - P - Next = P - Next - Next; - } + Else - P = P - Next; + } A at return h - Next; - } - };
Reprint please indicate source: Leetcode---82. Remove duplicates from Sorted List II
Leetcode---82. Remove duplicates from Sorted List II