码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 【 Remove Duplicates from Sorted List 】 python 实现

时间:2014-12-26 16:23:24      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

题目

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变化。

leetcode 【 Remove Duplicates from Sorted List 】 python 实现

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!