Remove Duplicates from Sorted List
问题描述:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
测试代码:
/**
* 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)
return head;
ListNode* p = head;
ListNode* pos = head->next;
int v = head->val;
while(pos)
{
if(pos->val==v)
{
p->next = pos->next;
pos = pos->next;
}else{
v = pos->val;
pos = pos->next;
p = p->next;
}
}
return head;
}
};