首页 > 试题广场 >

删除有序链表中重复的元素-I

[编程题]删除有序链表中重复的元素-I
  • 热度指数:162869 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次
例如:
给出的链表为,返回.
给出的链表为,返回.

数据范围:链表长度满足 ,链表中任意节点的值满足
进阶:空间复杂度 ,时间复杂度
示例1

输入

{1,1,2}

输出

{1,2}
示例2

输入

{}

输出

{}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        cur = head

        while cur and cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next

        return head

发表于 2023-10-08 23:17:21 回复(0)
#第一种
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        num = []
        while head:
            if head.val not in num:
                num.append(head.val)
                head = head.next
            else:
                head = head.next
               
        new = ListNode(-1)
        cur = new
        for i in num:
            cur.next = ListNode(i)
            cur = cur.next
        return new.next


#第二种
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        if head == None:
            return head

        pre = head
        while pre and pre.next:        
            cur = pre.next
            if cur.val == pre.val:
                pre.next = cur.next  
            else:
                pre = cur
        return head


发表于 2023-06-10 18:41:55 回复(0)
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#

# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        new_list = []
        if head == None:
            return head
        while head:
            new_list.append(head.val)
            head = head.next
        tmp = set(new_list)
        a = list(tmp)
        a.sort()
        #print(a)
        head = ListNode(0)
        cur = head

        for i in range(len(a)):
            cur.next = ListNode(a[i])
            cur = cur.next
        return head.next
发表于 2023-03-23 12:18:29 回复(0)
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        cur = head
        while cur and cur.next:
            nex = cur.next
            if nex.val <= cur.val:
                cur.next = nex.next
            else:
                cur = nex
        return head
发表于 2022-09-30 21:51:48 回复(0)
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        cur = head
        while cur:
            while cur.next and cur.val == cur.next.val:
                cur.next = cur.next.next
            cur = cur.next
        return head
发表于 2022-04-05 10:59:47 回复(0)