【题目描述】Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->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==NULL||head->next==NULL)
return head;
ListNode* p=head;
ListNode* q=head->next;
while(q!=NULL){
if(q->val==p->val) {
q=q->next;
}else{
p->next=q;
p=q;
q=q->next;
}
}
p->next=NULL;
return head;
}
};