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

删除链表中重复的结点

https://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 == NULL)
            return NULL;
        ListNode* res = new ListNode(0);
        //在链表前加一个表头
        res->next = pHead;
        ListNode* cur = res;
        while(cur->next != NULL && cur->next->next != NULL){
            //遇到相邻两个节点值相同
            if(cur->next->val == cur->next->next->val){
                int temp = cur->next->val;
                //将所有相同的都跳过
                while (cur->next != NULL && cur->next->val == temp)
                    cur->next = cur->next->next;
            }
            else
                cur = cur->next;
        }
        //返回时去掉表头
        return res->next;
    }
};

注意加表头的方法,以及新建 一个遍历用的当前节点,遇到下一个节点和下下个节点相同,则删去相同的所有节点

全部评论

相关推荐

精致的小松鼠人狠话不多:哈哈哈 我每次都差点点一下
点赞 评论 收藏
分享
白也ya:今天也是狠狠的被boss拷打了😋,终于知道双非想约到面试有多难了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务