第一题 https://leetcode.cn/problems/remove-linked-list-elements/submissions/691848826/
python
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
from typing import Optional
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next
注意cur.next为待删除目标时cur不往后移,因为后面还可能是相同元素。虚拟头结点还是挺方便的。
第二题 反转链表https://leetcode.cn/problems/reverse-linked-list/description/
python
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
代码不难,也用不着虚拟头结点。
第三题 https://leetcode.cn/problems/design-linked-list/description/
设计类的还是有点难度的,注意索引是否越界要提前判断,首尾插入都应该是按索引插入的特例