LeetCode 83.Remove Duplicates from Sorted List

题目描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list

思路

递归

迭代

c++

// 迭代
/** 
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode real_head(-1);
        real_head.next = head;
        ListNode *p = &real_head, *q = head;
        while(q){
            while(q -> next && q -> next -> val == q -> val) 
                q = q -> next;
            if(p -> next == q) 
                p = q;
            else {
                p ->next = q;
                p = p->next;
            }
            q = q -> next;
        }
        return real_head.next;
    }
}; 
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
         if (head == nullptr)    return nullptr;
        ListNode *p = head;
        while(p->next != nullptr && p->val == p->next->val)
            p = p->next;
        if(head == p){
            head->next =  deleteDuplicates(head->next);
            return head;
        }
        else
            return deleteDuplicates(head->next);
    }   
};
发布了61 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/HaoTheAnswer/article/details/104350443