LeetCode刷题(15)【简单】删除链表中重复元素(C++)

2023-05-13 13:26:46 浏览数 (1)

83. 删除排序链表中的重复元素


题目——链接


单指针法

代码语言:javascript复制
//一个指针往后遍历
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)
        {
            return head;
        }
        ListNode* tempnode = head;//这个头结点里面好像有元素
        while(tempnode->next)
        {
            if(tempnode->val == tempnode->next->val)
            {
                tempnode->next = tempnode->next->next;
            }
            else
            {
                tempnode = tempnode->next;
            }
        }
        return head;
    }
};

双指针-前后指针法

注意前后指针的链接

代码语言:javascript复制
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)
        {
            return head;
        }
        ListNode* Prev = head;
        ListNode* Next = head->next;

        while(Next)
        {
            if(Prev->val == Next->val)
            {
              
               Prev->next = Next->next;
               Next = Next->next;               
            }
            else
            {
                Prev= Next;
                Next = Next->next;
            }
        }
        return head;
    }
};

递归法

感谢这位老哥的分享——链接

代码语言:javascript复制
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)
        {
            return head;
        }
        head->next = deleteDuplicates(head->next);
        if(head->val == head->next->val)
        {
            head = head->next;
        }
        
        return head;
    }
};

图解:

0 人点赞