快乐的LeetCode --- 83. 删除排序链表中的重复元素

本文介绍了解决LeetCode上删除排序链表中重复元素问题的两种方法,通过遍历链表并比较相邻节点值,若相等则跳过重复节点,确保每个元素仅出现一次。提供Python和C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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

示例 1:

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

示例 2:

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

解题思路1:

类似题解:面试题18. 删除链表的节点


代码1: 超出时间限制

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        pre, cur = head, head.next
        while pre and cur:
            if pre.val == cur.val:
                pre.next = cur.next
            else:
                pre, cur = cur, cur.next

        return head

解题思路2:

类似题解:面试题18. 删除链表的节点


代码2:

写法1:

# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        res = head
        while res and res.next:
            if res.val == res.next.val:
                res.next = res.next.next 
            else:
                res = res.next
        return head

写法2:

# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        if not head: return None
        pre, cur = head, head.next
        while pre and cur:
            if pre.val == cur.val:
                pre.next = cur.next
                cur = cur.next
            else:
                pre, cur = cur, cur.next
        return head

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) {
        auto cur = head;
        while(cur){
            if (cur -> next && cur -> next -> val == cur -> val)
                cur -> next = cur -> next -> next;
            else
                cur = cur -> next;
        }
        return head;
    }
};

参考链接:

面试题18. 删除链表的节点


题目来源:

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list


同类题目:

[1]. 面试题18. 删除链表的节点
[2]. 237. 删除链表中的节点
[3]. 876. 链表的中间结点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值