代码随想录算法训练营|203.移除链表元素; 707.设计链表; 206.反转链表
203.移除链表元素
题目链接: 203.移除链表元素
文档讲解: 代码随想录
题目难度:简单
思路:掌握了链表的初始化定义
时间复杂度:O(log(n));空间复杂度:O(1)
下面展示 代码
:
class ListNode:
def __init__(self, val, next=None) -> None:
self.val = val
self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if head == None:
return None
else:
root = ListNode(next=head)
current = root
while current.next:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
return root.next
707.设计链表
题目链接: 707.设计链表
文档讲解: 代码随想录
题目难度:中等
思路:掌握了虚拟头结点,思路不难,但是判断index和链表长度的地方需要思路清晰,同时判断循环条件需要注意
代码
如下
class ListNode:
def __init__(self, val=0, next = None) -> None:
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
# 虚拟头结点
self.head = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index == None or index >= self.size:
return -1
else:
current = self.head.next
for i in range(index):
current = current.next
return current.val
def addAtHead(self, val: int) -> None:
# 添加至表头
self.head.next = ListNode(val, self.head.next)
# 等同于如下
# node = ListNode(val)
# node.next = self.head.next
# self.head.next = node
self.size += 1
# def addAtTail(self, val: int) -> None:
# if self.size == 0:
# self.head.next = ListNode(val)
# else:
# # 找到头节点
# current = self.head.next
# while current.next:
# current = current.next
# # 添加至表尾
# current.next = ListNode(val)
# self.size += 1
def addAtTail(self, val: int) -> None:
current = self.head
while current.next:
current = current.next
# 添加至表尾
current.next = ListNode(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index == 0:
self.addAtHead(val)
# index大于链表的长度
elif index > self.size or index < 0:
pass
elif index == self.size:
self.addAtTail(val)
else:
current = self.head
for i in range(index):
current = current.next
current.next = ListNode(val, current.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index < self.size:
# 下标有效
current = self.head
for i in range(index):
current = current.next
current.next = current.next.next
self.size -= 1
206.反转链表
题目链接: 206.反转链表
文档讲解: 代码随想录
题目难度:简单
思路:注意循环条件为cur不为空
时间复杂度:O(n)
acm模式代码
如下
class ListNode:
def __init__(self, val=0, next = None) -> None:
self.val = val
self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre, cur = None, head
while cur.next:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
cur.next = pre
return pre