题解 | #删除链表中重复的结点#

删除链表中重复的结点

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        if(pHead == nullptr || pHead->next == nullptr)
            return pHead;
        ListNode* preHead = new ListNode(0);		//这里创建一个新节点,可以规避掉头节点是重复值的情况,达到统一处理的效果
        preHead->next = pHead;
        ListNode* pre = preHead;
        ListNode* cur = pHead;
        while(cur){
            ListNode* nextDifferent = cur->next;
            while(nextDifferent && nextDifferent->val == cur->val)		//nextDifferent表示下一个不同数的节点
                nextDifferent = nextDifferent->next;
            if(cur->next == nextDifferent){		//如果代表前后两个数不同,那么可以更新pre和cur
                pre->next = cur;
                pre = cur;
                cur = nextDifferent;
            }else{
                cur = nextDifferent;		//这里表示当前cur有重复值,那么就把cur更新到下一个数,pre不动
            }
        }
        pre->next = cur;
        return preHead->next;
    }
};
全部评论

相关推荐

2 收藏 评论
分享
牛客网
牛客企业服务