题目:
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==NULL)return NULL;
ListNode* res=new ListNode(head->val);
ListNode* next=res;
head=head->next;
while(head!=NULL){
if(head->val!=next->val){
ListNode* tmp=new ListNode(head->val);
next->next=tmp;
next=tmp;
}
head=head->next;
}
return res;
}
};