# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
virtual_head = ListNode(next = head)
node = virtual_head
while node.next != None:
if node.next.val == val:
node.next = node.next.next
else:
node = node.next
return virtual_head.next
时间O(n),空间O(1)。题目的头节点head是链表的第一个节点,创建虚拟头节点virtual_head,指向链表的第一个节点。从virtual_head开始,检查当前节点node的下一个节点的值,若为val则删去node的下一个节点,即令node指向node.next.next;若不为val,node后移一位(易错),循环。注意不要直接返回虚拟头节点。
class my_node:
def __init__(self, val = -1, next = None, prev = None): #val default = -1 是为了方便 self.get(index_out_of_range)
self.val = val
self.next = next
self.prev = prev
class MyLinkedList(object):
def __init__(self): #虚拟头节点、虚拟尾节点
self.head = my_node()
self.tail = my_node()
self.head.next = self.tail
self.tail.prev = self.head
def get(self, index):
if index < 0:
return -1
i = 0
cur_node = self.head
while i <= index and cur_node.next != None:
cur_node = cur_node.next
#此时cur_node的下标==i
i += 1
return cur_node.val
#若index<len,是有效的下标,退出循环时节点就是cur_node
#若index>=len,过大的下标,退出循环时节点==虚拟尾节点,返回其值-1
def addAtHead(self, val):
old_head = self.head.next
new_head = my_node(val, old_head, self.head)
self.head.next = new_head
old_head.prev = new_head
def addAtTail(self, val):
old_tail = self.tail.prev
new_tail = my_node(val, self.tail, old_tail)
self.tail.prev = new_tail
old_tail.next = new_tail
def addAtIndex(self, index, val):
if index >= 0:
i = 0
cur_node = self.head
while i <= index and cur_node.next != None: #cur_node最多可取到虚拟尾节点(此时在虚拟尾节点前add node
cur_node = cur_node.next
i += 1
if i == index + 1: #若退出循环时cur_node下标==index,说明index没有超出限制,可以add node
old_prev = cur_node.prev
new_node = my_node(val, cur_node, old_prev)
old_prev.next = new_node
cur_node.prev = new_node
def deleteAtIndex(self, index):
if index >= 0:
i = 0
cur_node = self.head
while i <= index and cur_node.next != self.tail: #cur_node最多可取到最后一个元素(因为删除虚拟尾节点无意义
cur_node = cur_node.next
i += 1
if i == index + 1: #若退出循环时cur_node下标==index,说明index没有超出限制,可以del node
old_prev = cur_node.prev
old_next = cur_node.next
old_prev.next = old_next
old_next.prev = old_prev
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
#解法一:双指针
class Solution(object):
def reverseList(self, head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
#解法二:递归(注意return,即程序的出口
class Solution(object):
def reverseList(self, head):
return self.reverse(head, None)
def reverse(self, cur, pre):
if cur == None:
return pre
tmp = cur.next
cur.next = pre
return self.reverse(tmp, cur)