problem:
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
.
thinking:
(1)单链表顺序遍历,时间复杂度O(n),这道题不难
(2)我采用双指针法遍历,用前驱指针保存最近出现的非重复结点,方便删除重复的结点,一次提交AC
code:
/** * 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; if(head->val==head->next->val)//从头结点开始出现重复元素 { ListNode *tmp=head;; while(tmp->next && tmp->val==tmp->next->val) { tmp=tmp->next; } return deleteDuplicates(tmp->next); } ListNode *p=head;//左指针 ListNode *q=p; //右指针 ListNode *pre=p; //前驱指针 while(p!=NULL) { q=p->next; //右指针初始化 if(q==NULL) return head; if(p->val!=q->val) //不相等,同时前进 { pre=p; //前驱指针保存最后一次出现的非重复结点 p=p->next; q=q->next; } else //相等 ,右指针前进 { while(q!=NULL && q->val==p->val) { q=q->next; } pre->next=q; //删除重复元素 p=q; //更新左指针 } } return head; } };
leetcode || 82、Remove Duplicates from Sorted List II
原文地址:http://blog.csdn.net/hustyangju/article/details/45028247