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
相关问题1:压缩字符串
相关问题2:Remove Duplicates from Sorted Linked List I 从排序链表中去掉重复值
相关问题3:[LeetCode] Remove Duplicates From Sorted Array I
相关问题 4: [LeetCode] Remove Duplicates From Sorted Array II代码:
/**
* 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) {
int count = 0;
ListNode* newHead=NULL;
ListNode* slow = NULL;
ListNode* fast = head;
if(head==NULL) return NULL;
if(head->next==NULL) return head;
while(fast->next)
{
if(fast->val==fast->next->val) // A[j-1]==A[j]
{
count++;
fast=fast->next;
}
else // A[j-1]!=A[j]
{
count++;
if(count==1)
{
if(slow==NULL)
newHead = fast;
else
slow->next = fast;
slow = fast;
fast = fast->next;
slow->next=NULL;
count=0;
}
else
{
fast = fast->next;
count = 0;
}
}
}
count++;
if(count==1)
{
if(slow==NULL)
newHead = fast;
else
slow->next = fast;
slow = fast;
slow->next=NULL;
}
fast = fast->next;
return newHead;
}
};