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
.
两种方法
方法一:遍历链表两次,第一次去除重复节点,并把每次删除的结点值保存到容器当中(保存过的值不再保存),第二次遍历,取出容器中的值,并删除链表中相同值的结点;
方法二:一次遍历,指针比较容易出错;
其实,两种方法时间复杂度是一样的,但方法一用到了辅助空间,方法二没有。
方法一:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ ListNode* deleteDuplicates(ListNode* head) { if(head==NULL) return NULL; if(head->next==NULL) return head; vector<int> deleteValue; ListNode* p=head; int key=p->val; p=p->next; ListNode* q=head; bool flag=false; while(p) { if(p->val==key) { ListNode* toBeDeleted=p; q->next=toBeDeleted->next; p=q->next; delete toBeDeleted; toBeDeleted=NULL; if(!flag) { deleteValue.push_back(key); flag=true; } } else { key=p->val; flag=false; p=p->next; q=q->next; } } p=head; q=head; vector<int>::iterator iter=deleteValue.begin(); while(p && iter!=deleteValue.end()) { if(p->val==*iter) { if(p==head) { ListNode* toBeDeleted=p; p=toBeDeleted->next; q=toBeDeleted->next; head=q; delete toBeDeleted; toBeDeleted=NULL; } else { ListNode* toBeDeleted=p; q->next=toBeDeleted->next; p=q->next; delete toBeDeleted; toBeDeleted=NULL; } iter++; } else { if(p!=q) q=q->next; p=p->next; } } return head; }方法二:
/** * 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; if(head->next==NULL) return head; ListNode* p=head; ListNode* q=head; ListNode* k=p->next; bool flag=false; while(k) { if(p->val==k->val) { if(p==q) { p=q=k; head=k; k=k->next; } else { ListNode* toBeDeleted=k; p->next=toBeDeleted->next; k=p->next; delete toBeDeleted; toBeDeleted=NULL; } flag=true; } else { if(flag) { if(p==q) { p=q=k; head=k; k=k->next; flag=false; } else { ListNode* toBeDeleted=p; q->next=toBeDeleted->next; p=k; k=k->next; delete toBeDeleted; toBeDeleted=NULL; flag=false; } } else { if(p!=q) q=q->next; p=p->next; k=k->next; } } } if(flag) { if(p==q) { delete p; p=NULL; return NULL; } ListNode* toBeDeleted=p; q->next=toBeDeleted->next; delete toBeDeleted; toBeDeleted=NULL; } return head; } };