LeetCode小白菜笔记[20]:Remove Duplicates from Sorted List

LeetCode小白菜笔记[20]:Remove Duplicates from Sorted List

83. Remove Duplicates from Sorted List [easy]

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.

从一个有序链表中去重。由于是链表,可能会简单一些,因为不需要进行移动,也不需要重新开一段储存区域,只需要将重复的skip过去,然后把链表中的link从上一个数值的头一个链接到下一个数值的头一个。

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

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return None
        thispt = head
        while not thispt.next == None:
            if thispt.val == thispt.next.val:
                thispt.next = thispt.next.next
            else:
                thispt = thispt.next
        return head

while循环的终点应当是self.next == None,因为比较的是self.val和self.next.val,如果self.next == None了,后一项就取不出val。另外,注意特殊情况,比如head == None。另外,python中的链表中最后的NULL用的是None指代。

51ms,67.55%

2018年2月11日23:03:11

打嗝使我难受,嗝~

posted @ 2018-02-11 23:05  毛利小九郎  阅读(60)  评论(0编辑  收藏  举报