lintcode练习- 112. 删除排序链表中的重复元素

给定一个排序链表,删除所有重复的元素每个元素只留下一个。

样例

给出 1->1->2->null,返回 1->2->null

给出 1->1->2->3->3->null,返回 1->2->3->null

实现代码:

注意对结尾特殊处理

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: head is the head of the linked list
    @return: head of linked list
    """
    def deleteDuplicates(self, head):
        # write your code here
        if head is None or head.next is None:
            return head
        pre = head
        cur = head
        while cur:
            if pre.val == cur.val:
                cur = cur.next
            else:
                pre.next = cur
                pre = cur
                cur = cur.next
        if pre and pre.next:
            pre.next = None
        return head
                
 

你可能感兴趣的:(#,lintcode,#,算法,python,#,lintcode练习笔记)