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 有另一種方法,而這裏是通過儲存值的列表來確保無重複。