leetcode-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.

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

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

思路:记录当前节点,当前节点的前一个节点,当前节点的后一个节点;

          首先找到第一个不重复的头节点,前一个节点和当前节点若相等,则注意更新头节点。

         

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
         if(head == NULL)
            return NULL;
         if(head->next == NULL)
            return head;
         int flag = 1;
         ListNode * pre;/*后一个 节点*/
         ListNode * p;/* 当前节点*/
         ListNode * last;/*重复节点的前一个*/
         ListNode * q;/*删除的临时节点*/
         /*得到第一个不重复的head*/
         pre = head->next;
         p = head;
         while(p->val == pre->val && pre!=NULL)
         {
             flag = 0;
             head = head->next;
             p = p->next;
             pre = pre->next;
             if(head == NULL)
                return NULL;
             if(pre == NULL)
                return NULL;
         }
         if(flag == 0)
         head = head ->next;/*head 不重复*/

         //printf("%d %d\n",head->val,head->next->val);
         if(head->next == NULL)
            return head;

         if(head->val == head->next->val && head->next == NULL)
         {
             return NULL;
         }

         pre = head->next;
         p = head;
         last = p;

         while(pre != NULL)
         {
             flag = 1;
             while(pre != NULL && (pre->val == p->val))
             {
                 flag = 0;
                 q = pre;
                 pre = pre->next;
                 p->next = pre;
                 delete(q);
             }
             if(flag == 0)
             {
                 if(pre == NULL)
                 {
                    if(last == p)
                        return NULL;

                    last->next = NULL;
                    return head;
                 }
                 else
                 {
                     if(last == p)
                     {
                         head = head->next;
                         p = head;
                         last = p;
                         pre = pre->next;
                         continue;
                     }
                     q = p;
                     p = last;
                     p->next = pre;
                     delete(q);
                     p = p->next;
                     pre = pre->next;
                 }
                 flag = 1;
             }
             else
             {
                  last = p;
                  p = p->next;
                  pre=pre->next;
             }

         }
        return head;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值