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 ListNode
10     def deleteDuplicates(self, head):
11         if head is None or head.next is None:
12             return head
13         
14         dummyhead = ListNode(0)
15         dummyhead.next = head
16         p = dummyhead.next
17         
18         while p.next is not None:
19             if p.val == p.next.val:
20                 p.next = p.next.next
21             else:
22                 p = p.next
23         
24         return dummyhead.next

思路

设立虚表头dummyhead

遇上val不同的,再执行 p=p.next;否则指针p不动,只是p.next变化。

原文地址:https://www.cnblogs.com/xbf9xbf/p/4186734.html