首页 > 代码库 > leetcode 【 Remove Duplicates from Sorted List 】 python 实现
leetcode 【 Remove Duplicates from Sorted List 】 python 实现
题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
代码:
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @param head, a ListNode 9 # @return a ListNode10 def deleteDuplicates(self, head):11 if head is None or head.next is None:12 return head13 14 dummyhead = ListNode(0)15 dummyhead.next = head16 p = dummyhead.next17 18 while p.next is not None:19 if p.val == p.next.val:20 p.next = p.next.next21 else:22 p = p.next23 24 return dummyhead.next
思路:
设立虚表头dummyhead
遇上val不同的,再执行 p=p.next;否则指针p不动,只是p.next变化。
leetcode 【 Remove Duplicates from Sorted List 】 python 实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。