剑指offer:删除链表中重复的节点

题目描述

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

AC C++ Solution:

class Solution {
public:
    ListNode *deleteDuplication(ListNode *pHead) {
        ListNode **runner = &pHead;
        
        if(!pHead || !pHead->next) return pHead;
        
        while(*runner)
        {
            if((*runner)->next && (*runner)->next->val == (*runner)->val)
            {
                ListNode *temp = *runner;
                while(temp && (*runner)->val == temp->val)
                    temp = temp->next;
                
                *runner = temp;
            }
            else
                runner = &((*runner)->next);
        }
        
        return pHead;
    }
};

猜你喜欢

转载自blog.csdn.net/amoscykl/article/details/85548487