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

83. Remove Duplicates from Sorted List Leetcode Python

时间:2015-02-05 09:34:25      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   linklist   

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.


定义一个pre 和cur

1.当二者不等的时候pre.next=cur pre=pre.next

2.当相等的时候pre.next=cur.next

3.每步都是cur=cur.next

代码如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def deleteDuplicates(self, head):
        if head==None or head.next==None:
            return head
        dummy=ListNode(0)
        dummy.next=head
        pre=dummy.next
        cur=dummy.next
        while cur:
            if pre.val!=cur.val:
                pre.next=cur
                pre=pre.next
            else:
                pre.next=cur.next
            cur=cur.next
        return dummy.next



83. Remove Duplicates from Sorted List Leetcode Python

标签:leetcode   python   linklist   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/43503601

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