Leetcode82:remove duplicates from Sorted List II

Source: Internet
Author: User

Given a sorted linkedList, delete AllNodes that has duplicate numbers, leaving only distinct numbers from the originalList.For Example,given1 -2 -3 -3 -4 -4 -5,return 1 -2 -5.Given1 -1 -1 -2 -3,return 2 -3.
Solution One

My idea is that for a node of a linked list, we first find the duplicate elements of the node, then delete the duplicate elements, and then iterate over the linked list. The idea of first querying a repeating element and then deleting it requires three pointers, and there are different ways of dealing with duplicate elements in the chain header and duplicate elements in the middle of the linked list.
Consider the existence of duplicate elements in the chain header first: [1,1,1,2,3]:
Use three pointers First,second,third. First initially points to the element, second and Thrid point to the second element.
For cases where duplicate elements exist in the list header, only two pointers are used, where first and second are used

Compare the elements that first and second point to if they are equal, and then move the second to the right until you find an element that is not equal to the one that is pointed to. Such as:

The element is then removed from the [First,second] and the first point points to the same element second. At this point, if first is empty, it means that there are no elements behind the list, both second and third are null, and if first is not empty, second and third are moved forward one bit. You can then return to the while loop and then judge. The reason for using while without if is to handle such a test case: [1,1,2,2,3].

Above is the processing of duplicate elements in the linked header.
After processing, you can guarantee that the elements pointed to by first and second (second and third initially point to the same element) have different values. The point here is to judge how many of the second are behind if there are duplicate elements, and this is where the third pointer comes in handy. This pointer is used to point to the last node with the second pointer pointing to the same value as the node, for the test case of [1,2,2,2,3]:

Third initial and second point to the same element, which is a node behind first, since second has a node with the same value as the second element, the third pointer is moved back to the last node with the same value as the second element. The next pointer to first is pointed to the next node of Thrid, and then the elements between second and third are removed. Then update the location of second and third.
C + + code implementation:
Runtime:11ms

/** * 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) {if(Head==NULL)return NULL;//using three pointers, the first pointer points to the last element that is not duplicated, the second pointer and the third pointer indicate the area where the number repeats    //Initial first pointer to the list header, second second and third second pointer to second elementListNode*First=Head ListNode*Second=Head -Next ListNode*Third=Head -Next//To determine if there are duplicate variables during traversalBOOL Repeat=false;//Special handling is required for the first duplicate element in the array    //At this time because the need to compare first and second points are equal, so they need to be in front of the two non-null judgment    //processing such a test case [1,1,2,2,3]     while(First!=NULL&&Second!=NULL&&First -Val==Second -Val) {//If the first and second elements are equal, you need to continue querying until you find the first unequal element, second points to it at this point         while(First!=NULL&&Second!=NULL&&First -Val==Second -Val) Second=Second -Next///Then start deleting elements until second, where the first pointer and second pointer point to the same nodeListNode*Tmp=First while(TMP!=Second) {First=First -Next            Delete tmp; Tmp=First }//Then judge the node above first and second, and if it is not empty, then second and third move backwards one        if(First!=NULL) {Second=First -Next Third=Second }Else//If this node is empty, indicating that no elements are present, then both the second and third pointers are set to null{Second=NULL; Third=NULL; }    }after the end of the loop, it is possible to determine the head pointer of the linked list after the element is deleted and save it. Head=First//Then start traversing the linked list     while(third!=NULL)    {//Determine if there are duplicate elements behind the first pointer and compare the next element of the third pointer to the element pointed to by the second pointer.        //until a different element is found, then the second element points to the first element of the repeating element,        //third points to the last element of the repeating element and records whether there are duplicate elements behind the first element         while(third!=NULL&&Third -Next!=NULL&&Second -Val==Third -Next -Val) {Third=Third -Next Repeat=true; }//If there are duplicate elements behind first, you need to remove the intermediate elements pointed to by the second and third pointers.         if(repeat) {//First point pointer to the next element of third, at which point the element must be different between second and thirdFirst -Next=Third -Next//start removing elements between [Second,third], including second and thirdListNode*Tmp=Second while(second!=Third -Next) {Second=Second -Next                Delete tmp; Tmp=Second }///Then move the second pointer back one bit and keep the second and third the sameSecond=First -Next Third=Second//After processing a repeating element, you need to reset the variable that determines the repeating element to falseRepeat=false; }Else//If the element behind the first is not a repeating element, then first plus 1, second and third point to the next element{First=Second Second=Second -Next Third=Second }    }returnHead;}};
Solution Two

See a lot of ways to use a pseudo-node in the discuss, using this pseudo-node can be in the chain header above the existence of duplicate elements and the intermediate existence of duplicate elements together, which can reduce a lot of code. And you can merge the duplicate query elements with the delete operation (in fact, the first query and then delete is a very foolish way, do not make this silly later). This makes the code very concise.
Note that the following Fakenode node is a pseudo-node, and the Prev pointer points to the previous non-repeating node of the current node. According to the meaning of prev, it can be found that Prev is Fakenode node initially. Because the Fakenode node initially points to the head node.
Runtime:8ms

/** * Definition forsingly-linked list. * struct ListNode {*intVal * ListNode *Next; * ListNode (intx): Val (x),Next(NULL) {} * }; */classSolution { Public: listnode* deleteduplicates (listnode* head) {ListNode * fakenode=NewListNode (0); Fakenode->Next=head; ListNode *prev=fakenode; while(head!=NULL)    {if(head->Next&&head->val==head->Next->val) {intvalue=head->val; while(Head&&head->val==value) {prev->Next=head->Next;                    Delete head; Head=prev->Next; }        }Else{prev=head; Head=head->Next; }} return fakenode->Next;}};

Leetcode82:remove duplicates from Sorted List II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.