82. 删除排序链表中的重复元素 II
82. 删除排序链表中的重复元素 II
题意
和1不同的是,1只删除一个重复数字,但是在2中需要删除所有含有重复数字的节点。
解题思路
我直接重新构造了一颗新的链表,没有在原链表的基础之上进行操作;
实现
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
listnode = ListNode(0)
temp = head
temp2 = listnode
while temp:
if temp.next and temp.val == temp.next.val:
start = temp
while start and start.val == temp.val:
start = start.next
temp = start
else:
temp2.next = ListNode(temp.val)
temp2 = temp2.next
temp = temp.next
return listnode.next
当然你也可以在原来链表的基础之上进行更改,如下:
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
listnode = ListNode('')
listnode.next = head
temp = listnode
prev = listnode
while temp:
if temp.next and temp.val == temp.next.val:
# 找到重复值截止的位置
start = temp
while start and start.val == temp.val:
start = start.next
# 将前结点的指向不重复值的结点
prev.next = start
temp = start
else:
# 正常移动
prev = temp
temp = temp.next
return listnode.next

关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法