2.1 Write code to remove duplicates from an unsorted linked list.
Follow up
How would-solve this problem if a temporary buffer isn't allowed?
This problem allows us to remove duplicates from the unordered list, and there are two similar problems in Leetcode that are the Remove duplicates from Sorted list removes duplicates from the ordered list and the Remove duplicates from Sorted list II Removes duplicates in an ordered list of two. Both of these are for the orderly chain list, and this problem is against the unordered list, in fact, the difficulty is not very large. Many problems with linked list processing require the creation of a dummy node in front of the head node in order to prevent the head node from being removed and to return to the new head node position. And this question does not need, because this question lets us delete duplicates the node, not all deletes, but will retain one, then regardless of the head node has duplicates, will retain. This problem we can use a hash table to solve, the idea is for each node, if the hash table exists, then delete, if not, then add a hash table, see the code as follows:
classSolution { Public: ListNode*deleteduplicates (ListNode *head) {ListNode*pre = NULL, *cur =Head; intm[ the] = {0}; while(cur) {if(M[cur->val] >0) {Pre->next = cur->Next; } Else { ++m[cur->Val]; Pre=cur; } cur= cur->Next; } returnHead; }};
The problem of follow up let us not use the extra space, that is, the space complexity should be O (1), then we need two while loop to solve, we need two pointers, the first pointer to a node, the second pointer from the next position to start traversing to the end of the list, encountered the same delete. And so on until the first pointer completes the list of traversal can delete all duplicates, the overall idea and bubble sort somewhat similar, but this method of time complexity is O (N2), is a time to exchange space for the method, see code as follows:
classSolution { Public: ListNode*deleteduplicates (ListNode *head) {ListNode*pre = head, *cur =Head; while(PRE) {cur= pre->Next; while(cur) {if(Cur->val = = pre->val) {Pre->next = cur->Next; } cur= cur->Next; } Pre= pre->Next; } returnHead; }};
[Careercup] 2.1 Remove duplicates from unsorted list to remove duplicates from unordered list