2. Remove duplicate elements from an ordered list and array remove duplicates

Source: Internet
Author: User

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

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.