c++

删除链表中重复的结点

http://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if (pHead == NULL || pHead->next == NULL) return pHead;
        ListNode *cur = pHead, *pre = NULL;
        while(cur) {
            ListNode* p = cur->next;
            bool needDelete = false;
            if (p && p->val == cur->val) {
                needDelete = true;
            }
            if (!needDelete) {
                pre = cur;
                cur = cur->next;
            } else {
                ListNode* pDelNode = cur;
                int value = cur->val;
                while(pDelNode && pDelNode->val == value) {
                    ListNode* next = pDelNode->next;
                    delete pDelNode;
                    pDelNode = NULL;
                    pDelNode = next;
                }
                if (pre == NULL) {
                    pHead = pDelNode;
                } else {
                    pre->next = pDelNode;
                }
                cur = pDelNode;
            }
        }
        return pHead;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 15:46
已编辑
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务