1. Linked list Remove duplicates from Sorted List
Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Ideas:
There are generally two ways to implement a linked list: recursive and non-recursive
Recursive implementations:
ListNode*H=Headif(h== NULL)return NULL;if(h -Next!= NULL &&H -Next -Next!= NULL &&H -Val==H -Next -Val) H -Next=H -Next -Next H -Next=Deleteduplicates (H -Next);returnH
Because it is possible for more than 3 consecutive identical elements to be present, there is more to be considered for the right shift of a pointer. In the program below, when the element is equal, when the second element is deleted, the pointer shifts to the right, at which point the 3rd element is the starting recursion, and if the 3rd element and the 1th element are equal, an error occurs. It is more complicated to write correctly.
Non-recursive implementations:
/** * 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) {listnode* h = head;if(h = = NULL)returnNULL; listnode* t = NULL; while(h! = NULL) {T = h;//reference pointers while((h = h->next)! = NULL)//Cycle right until unequal{if(t->Val= = H->Val)Continue;Else Break; } t->next = h; }returnHead }};
Leetcode results:
Submission Details
164/164 Test cases passed.
status:accepted
Runtime:17 ms
2. Remove duplicate elements from an ordered list and array remove duplicates