Leetcode title: Remove Duplicates from Sorted List

Source: Internet
Author: User

Title: 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 .

Answer: Using three pointers, p identifies the linked list parts that have been processed, and q is used to refer to the node that is currently being compared, and R is used to iterate over whether there are duplicate elements.

Also use virtual header nodes to avoid too much judgment.

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) {
ListNode * Head = new ListNode (-1);
Head, next = head;
ListNode *p = Head;
ListNode *q = P-Next;
while (q! = NULL)
{
ListNode *r = q-Next;
while ((r! = NULL) && (r-val = = Q-val))
{
ListNode *tmp = R, Next;
Delete R;
R = tmp;
}
Q-next = R;
P-next = q;
p = q;
Q = q-Next;
}
ListNode *tmp = Head, Next;
Delete Head;
return TMP;
}
};

Leetcode title: Remove Duplicates from Sorted 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.