码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted List

时间:2015-06-29 11:26:25      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Remove Duplicates from Sorted List 

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 {ListNode} head
 9     # @return {ListNode}
10     def deleteDuplicates(self, head):
11         if head==None or head.next==None:
12             return head
13         p=head
14         while p.next:                    #前面的if判断已保证此时p!=None,此时仅判断p.next
15             if p.val==p.next.val:        #若此时p值与p.next值相等
16                 p.next=p.next.next       #去掉p.next,直接连到p.next.next,此时不需更改p,通过while仍然比较此时的p和p.next
17             else:                        
18                 p=p.next                 #若p和p.next值不等,移动p的位置,开始判断下一个节点和其后所跟的值。
19         return head

 

Remove Duplicates from Sorted List

标签:

原文地址:http://www.cnblogs.com/lzsjy421/p/4606991.html

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