首页 > 代码库 > LeetCode82 Remove Duplicates from Sorted List II

LeetCode82 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.(Medium)

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

分析:

链表去重的follow-up,但是题号这个在前面,要把有重复元素,则所有该元素均删掉。

注意:

1. 使用dummy node处理头结点被删除掉的情况。

2. 只要有head-> next -> val存在时,先判断head -> next是否为空。

代码:

 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         ListNode dummy(0);13         dummy.next = head;14         head = &dummy;15         while(head -> next != nullptr && head -> next -> next != nullptr) {16             if (head -> next -> val == head -> next -> next -> val) {17                 int val = head -> next -> val;18                 while (head -> next != nullptr && head -> next -> val == val) { //只要取head->next,先判断19                     ListNode* temp = head -> next;20                     head -> next = head -> next -> next;21                     delete temp;22                 }23             }24             else {25                 head = head -> next;26             }27         }28         return dummy.next;29     }30 };

 

 

LeetCode82 Remove Duplicates from Sorted List II