083. Remove Duplicates from Sorted List

题目链接:https://leetcode.com/problems/rotate-list/description/

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

思路:

  • 有序的链表中删除有重复值的结点。
  • 需要两个指针分别指向链表的第一个结点和第二个结点(如果存在),这两个指针分别为precur; 判断这两个指针所指向结点的值是否相等。
    1. 若相等,则改变指针指向对多余元素进行删除;
    2. 若不等,则pre = cur ; cur = cur->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        if (head == nullptr) return head;
13 
14        ListNode *cur = head;
15        ListNode *pre = nullptr;
16        
17        while ( cur->next != nullptr)
18        {
19              pre = cur;
20              cur = cur->next;
21              while ( cur != nullptr && pre->val == cur->val)
22              {
23                    pre->next = cur->next;
24                    cur = cur->next;
25              }
26              
27              // 应考虑到链表的尾节点为多余元素的情况
28              if (cur == nullptr)
29              {
30                    return head;
31              }
32        }
33        
34        return head;      
35     }
36 };

猜你喜欢

转载自www.cnblogs.com/ming-1012/p/9902634.html