class Solution(object):
def removeElements(self, head, val):
dummy = ListNode()
dummy.next = head
tmp = head
prev = dummy
while tmp:
if tmp.val == val:
prev.next = tmp.next
else:
prev = tmp
tmp = tmp.next
return dummy.next
时间复杂度:O(n)
空间复杂度:O(1)
707 设计链表
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList(object):
def __init__(self):
self.head = None
self.size = 0
def get(self, index):
if index < 0 or index >= self.size:
return -1
current = self.head
for _ in range(0, index):
current = current.next
return current.val
def addAtHead(self, val):
self.addAtIndex(0, val)
def addAtTail(self, val):
self.addAtIndex(self.size, val)
def addAtIndex(self, index, val):
if index > self.size:
return
current = self.head
new_node = ListNode(val)
if index <= 0:
new_node.next = current
self.head = new_node
else:
for _ in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.size += 1
def deleteAtIndex(self, index):
if index < 0 or index >= self.size:
return
current = self.head
if index == 0:
self.head = self.head.next
else:
for _ in range(0, index - 1):
current = current.next
current.next = current.next.next
self.size -= 1
206 反转链表
class Solution(object):
def reverseList(self, head):
prev = None
current = head
while current:
nex = current.next
current.next = prev
prev = current
current = nex
return prev