LeetCode(82)题解: Remove Duplicates from Sorted List II

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

题目:

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.

思路:

需要两个指针,a用来纪录新链表,b用来遍历老链表,因为只有删除操作,需要一个flag标记ab段要不要删除。此外要注意头节点的处理。

AC代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* deleteDuplicates(ListNode* head) {
12         if(head==NULL)
13             return NULL;
14         ListNode* newhead=new ListNode(0);  // to handle head
15         newhead->next=head;
16         ListNode* a=newhead,*b=newhead->next;
17         int now=head->val;
18         bool occur_flag=false;
19         while(b->next!=NULL){
20             if(b->next->val==now){
21                 occur_flag=true;
22             }
23             else{
24                 if(occur_flag==true){
25                     a->next=b->next;  //delete duplicate numbers
26                     b=a;    //update pointers
27                 }
28                 else{
29                     a=b;
30                 }
31                 occur_flag=false;
32                 now=b->next->val;
33             }
34             b=b->next;
35         }
36         if(occur_flag==true){
37             a->next=b->next;  //delete duplicate numbers
38             b=a;    //update pointers
39         }
40         else{
41             a=b;
42         }
43         return newhead->next;
44     }
45 };
原文地址:https://www.cnblogs.com/aezero/p/4713376.html