给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
# 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 not head:
return None
t = head
while t.next:
if t.val != t.next.val:
t = t.next
else:
t.next = t.next.next
return head
思路:遍历链表,比较当前节点的值和后一个节点的值,如果相等则把后面节点移到当前节点的位置。
创建链表函数,输入为列表,输出头节点
def createlist(l):
head = None
th = None
for i in l:
t = ListNode(0)
if not head:
t.val = i
head = t
th = head
else:
t.val = i
th.next = t
th = th.next
return head