【剑指offer】删除链表中重复的结点(链表)

版权声明:本文为原创博客,未经允许,请勿转载。 https://blog.csdn.net/u013095333/article/details/88600945

题目描述

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

链接

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=11209&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

代码

class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if(pHead == NULL){
            return NULL;
        }
        ListNode* ans = new ListNode(-1);
        ans->next = pHead;
        ListNode* link = ans;
        ListNode* start = ans->next;
        ListNode* end = ans->next;
        while(start){
            while(end && start->val == end->val){
                    end = end->next;
            }
            if(start->next == end){
                link->next = start;
                link = link->next;
                if(start){
                    start = start->next;
                }
                if(end){
                    end = end->next;
                }
            }
            else{
                start = end;
            }
        }
        link->next = NULL;
        return ans->next;
    }
};

猜你喜欢

转载自blog.csdn.net/u013095333/article/details/88600945