Title:
T83.Remove Duplicates from Sorted List
Related Topics:
LinkedList
Describe:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Sample Input&output:
1. Input: 1->1->2
Output: 1->2
2. Input: 1->1->2->3->3
Output: 1->2->3
Code:
# 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:
val_list = []
val_list.append(head.val)
first = ListNode(head.val-1)
first.next = head
while head and head.next:
tmp = head.next
if tmp.val in val_list:
head.next = tmp.next
tmp = head.next
else:
val_list.append(head.next.val)
head = tmp
return first.next
Record:
- 循环遍历列表时,要注意while循环的条件,如果已经到了末尾,一个NoneType是没有next的,会报错。
- https://blog.csdn.net/Lynette_bb/article/details/73414134 有另一种方法,而这里是通过储存值的列表来确保无重复。