Leetcode 83. Remove duplicates from Sorted list linked list

Source: Internet
Author: User

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such this each element appear only once.

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

Main topic:

Remove the same elements within an ordered list, that is, the same element is reserved only one.


The code is as follows:

/** * 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;         ListNode* p = head->next;         listnode* pre = head;        int cur =  head->val;        while (p != null)          {                         if (Cur == p->val)              {                 pre->next = p->next;             }            else             {                 cur = p->val;                 pre = p;             }             p = p-> Next;        }        return  head;    }};

Other Concise practices:

1. Double while

Reference from: https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing


Class Solution {Public:listnode *deleteduplicates (ListNode *head) {listnode* cur = head;  while (cur) {while (cur->next && cur->val = = cur->next->val) Cur->next =            cur->next->next;        Cur = cur->next;    } return head; }};

2. Double pointer

Reference from: https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing

ListNode *deleteduplicates (ListNode *head) {listnode*cur=head,*tail=head;            while (cur) {if (cur->val!=tail->val) {tail->next=cur;        Tail=cur;        } cur=cur->next;    tail->next=null; } return head;


2016-08-12 12:37:15

This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1837260

Leetcode 83. Remove duplicates from Sorted list linked list

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.