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
.
相关问题1:压缩字符串
相关问题2-1:Remove Duplicates from Sorted Linked List I
相关问题2-2:[LeetCode] Remove Duplicates from Sorted List II
相关问题3:[LeetCode] Remove Duplicates From Sorted Array I
相关问题 4: [LeetCode] Remove Duplicates From Sorted Array II思路和相关问题3和相关问题4 完全一样:fast-val是和A[j-1] 相当,fast->next->val和A[j]相当。注意,新链表和原来的链表可能有不一样的头指针。
ListNode *deleteDuplicates(ListNode *head) {
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]
{
if(slow==NULL)
newHead = fast;
else
slow->next = fast;
slow = fast;
}
fast = fast->next;
}
if(slow==NULL)
newHead = fast;
else
slow->next = fast;
slow = fast;
fast = fast->next;
return newHead;
}