剑指offer56:删除链表中重复的结点,排序的链表中,删除重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

1 题目描述

  在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

2 思路和方法

  (1)链表为空,不必多说return NULL

  (2)如果恰恰是头结点与头结点的后一个重复了,这种情况是可以发生的,那头结点就要被删除,另选新的结点作为头结点。如何处理这种特殊情况,多申请一个指针就可以了。

3 C++核心代码

 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         if(NULL == pHead) return NULL; 
15         ListNode* pre = NULL, *cur = pHead;
16         while(NULL != cur){
17             if(NULL != cur->next && cur->val == cur->next->val){    //凡是涉及解引用,就要判空,这是职业素养!!!
18                 int repeat = cur->val;
19                 ListNode* pNext;
20                 while(NULL != cur && cur->val == repeat){    //通过循环删除所有值为repeat的结点
21                     pNext = cur->next;
22                     delete cur;
23                     cur = pNext;
24                 }
25             }else{
26                 pre = cur;    //pre指向不重复的结点
27                 cur = cur->next;
28             }
29             
30             if(NULL == pre){
31                 pHead = cur;
32             }else{
33                 pre->next = cur;
34             }
35         }
36         return pHead;
37     }
38 };
View Code

参考资料

https://blog.csdn.net/qq_41822235/article/details/82832898

猜你喜欢

转载自www.cnblogs.com/wxwhnu/p/11429134.html