[面试真题] LeetCode:Remove Duplicates from Sorted List I & II

Given a sorted linked list, delete all duplicates such that each element appear only once.

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

 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if(NULL == head){
15             return head;
16         }
17         int dup = head->val;
18         ListNode *p = head;
19         while(p->next){
20             if(dup == p->next->val){
21                 p->next = p->next->next;
22             }else{
23                 dup = p->next->val;
24                 p = p->next;
25             }
26         }
27         return head;
28     }
29 };

Run Status: Accepted!
Program Runtime: 84 milli secs

Progress: 164/164 test cases passed.
 

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.

解法: 记录重复部分左相邻节点tail,isdup用于判断当前节点是否重复。鉴于输入可能从一开始就重复,需设置新的头节点left。

 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if(NULL == head){
15              return head;
16          }
17          int dup = head->val;
18          ListNode *left = new ListNode(0);
19          left->next = head;
20          ListNode *tail = left, *p = head;
21          bool isdup = false;
22          while(p->next){
23              if(dup == p->next->val){
24                  p = p->next;
25                  tail->next = p->next;
26                  isdup = true;
27              }else{
28                  if(!isdup){
29                      tail = p;
30                  }
31                  dup = p->next->val;
32                  p = p->next;
33                  isdup = false;
34              }
35          }
36          return left->next;
37     }
38 };

Run Status: Accepted!
Program Runtime: 60 milli secs

Progress: 166/166 test cases passed.
原文地址:https://www.cnblogs.com/infinityu/p/3074317.html