Remove duplicates from Sorted List Leetcode

Source: Internet
Author: User

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 .

The title means to delete the repeating element in the linked list

Idea: Traverse the list, with two pointers, one pointing to the previous one, one pointing to the next, when the two points are not equal, while the backward, when two points to the same value, you need to delete an element (the value pointed to by the latter pointer), and then backward traversal

The code is as follows:

<span style= "FONT-SIZE:18PX;" >/** * Definition for singly-linked list. * struct ListNode {*     int val; *     ListNode *next; *     listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public:    listnode *deleteduplicates (ListNode *head) {               if (head==null| | Head->next==null)        return head;             ListNode *p,*q,*pur;        P=head;        q=p->next;    while (Q!=null)    {        if (p->val==q->val)        {            pur=q;            q=q->next;            p->next=q;            Delete pur;        }        else        {            p=q;            q=q->next;        }    }                return head;            }; </span>


Remove duplicates from Sorted List Leetcode

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.