剑指offer 面试题 删除链表中重复的节点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
 
写法1:
当前遍历到cur节点,如果cur->next和cur->next->next的值相同,说明找到了重复节点,然后新建一个指针nex,一直往后找,直到值不等于之前重复节点的val值。将cur和nex连起来即可。
如1,2,2,2,3
cur遍历到1,此时cur之后的两个节点都为2,那么nex一路往后找到3,将1和3连起来,这样就删除了所有值为2的节点。
 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6         val(x), next(NULL) {
 7     }
 8 };
 9 */
10 class Solution {
11 public:
12     ListNode* deleteDuplication(ListNode* pHead)
13     {
14         auto dummy=new ListNode(INT_MIN);
15         dummy->next=pHead;
16         auto cur=dummy;
17         while(cur->next and cur->next->next){
18             if(cur->next->val==cur->next->next->val){
19                 auto nex=cur->next;
20                 int temp=cur->next->val;
21                 while(nex and nex->val==temp){
22                     nex=nex->next;
23                 }
24                 cur->next=nex;
25             }
26             else{
27                 cur=cur->next;
28             }
29         }
30         return dummy->next;
31     }
32 };

写法2:

 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6         val(x), next(NULL) {
 7     }
 8 };
 9 */
10 class Solution {
11 public:
12     ListNode* deleteDuplication(ListNode* pHead)
13     {
14         auto dummy=new ListNode(INT_MIN);
15         dummy->next=pHead;
16         auto final_unique=dummy,cur=pHead,pre=dummy;
17         while(cur){
18             if(cur->next and cur->val==cur->next->val){
19                 while(cur->next and cur->val==cur->next->val){
20                     cur=cur->next;
21                 }
22                 //此时cur为最后一个重复节点
23             }
24             else{
25                 final_unique->next=cur;
26                 final_unique=cur;
27             }
28             cur=cur->next;
29         }
30         final_unique->next=nullptr;
31         return dummy->next;
32     }
33 };

猜你喜欢

转载自www.cnblogs.com/FdWzy/p/12305076.html