Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
给定一个有序链表,删出其中重复出现的值。 注意,Remove Duplicates from Sorted List使链表中的值唯一化,而本题是直接把有重复的值剔除。
/**
* 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 head;
if(head->next==NULL)return head;
ListNode*newHead=NULL;
ListNode*prev=NULL;
ListNode*cur=head;
while(cur){
if(cur->next!=NULL){
//判断当前结点值是否重复
if(cur->val == cur->next->val){
//如果判断是重复数字,则跳过与当前结点值相等的结点
int val = cur->val;
while(cur && cur->val==val)cur=cur->next;
}
else{
//如果不重复,则接到新链表上
if(prev==NULL) newHead=cur;
else prev->next=cur;
prev=cur;
cur=cur->next;
prev->next=NULL; //prev这里充当的是链表尾结点的角色,因此next指针需要置NULL
}
}
else{
//如果已经是最后一个结点,之间连到新链表上
if(prev==NULL)newHead=cur;
else prev->next=cur;
cur=cur->next;
}
}
return newHead;
}
};LeetCode: Remove Duplicates from Sorted List II [083],布布扣,bubuko.com
LeetCode: Remove Duplicates from Sorted List II [083]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/27666189