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