Remove Duplicates from Sorted List
算法太简单,就看实现简不简洁,这道题自己写的算法也能过,但是没有答案这么简单,其实说白了就是一个指针在当前位,然后看是否和相邻的相等,如果相等,则把当前节点的next跳到下下个去再来循环,有点类似搭桥的感觉
# 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
"""
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
Remove Duplicates from Sorted List II
和上题不同的是,这题一旦发现重复元素则将其全部删去一个不留,自己的代码也能过,但还是逻辑不好看,下面是干净的版本
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode('d')
dummy.next = head
pre, cur = dummy, head
while cur:
while cur.next and cur.val == cur.next.val:
cur = cur.next
if pre.next = cur:
pre = pre.next
else:
pre.next = cur.next
cur = cur.next
return dummy.next