题目描述:

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.

解题思路:

因为这道题是要把所有的重复节点删除,所以不能再比较下一个节点和当前节点是否相同再删除了。

我先生成了一个pre指针,把head指针当作cur指针,如果cur节点的下一个节点与cur节点(pre节点的下一个节点)相同,那么就将cur指针往下推,直到cur节点的下一个节点与pre节点的下一个节点不同或是等于NULL。然后再使pre的next等于head的下一个。一直重复操作直到head不存在或是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         if(!head || !head->next)
13             return head;
14         ListNode* pre = new ListNode(0), *p = pre;
15         pre->next = head;
16         while(head && head->next){
17             if(pre->next->val == head->next->val){
18                 while(head->next && pre->next->val == head->next->val)
19                     head = head->next;
20                 pre->next = head->next;
21                 head = head->next;
22             }
23             else{
24                 pre = pre->next;
25                 head = head->next;
26             }
27         }
28         return p->next;
29     }
30 };

 

 

 

posted on 2018-03-19 18:01  宵夜在哪  阅读(76)  评论(0编辑  收藏  举报