首页 > 其他 > 详细

Leetcode 83. Remove Duplicates from Sorted List

时间:2017-01-08 13:59:40      阅读:237      评论: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.

 

思路和在sorted array中去重差不多。注意L22如果不comment掉会出错。原因是,while head.next 要求list的长度至少为2。如果初始的list 是 1 -> 1 -> None。如果执行L22,那么head = None,while head.next 会出错。

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def deleteDuplicates(self, head):
 9         """
10         :type head: ListNode
11         :rtype: ListNode
12         """
13         if head == None or head.next == None:
14             return head
15         
16         dummy = head
17         while head.next:
18             if head.next.val != head.val:
19                 head = head.next
20             else:
21                 head.next = head.next.next
22         #        head = head.next
23         return dummy

 

Leetcode 83. Remove Duplicates from Sorted List

原文:http://www.cnblogs.com/lettuan/p/6261804.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!