class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_linked_list(nums):
if not nums:
return None
head = ListNode(nums[0])
current = head
for num in nums[1:]:
current.next = ListNode(num)
current = current.next
return head
def insert_node(head, val, pos):
new_node = ListNode(val)
if pos == 0:
new_node.next = head
return new_node
current = head
count = 0
while current and count < pos - 1:
current = current.next
count += 1
if current:
new_node.next = current.next
current.next = new_node
return head
def delete_node(head, val):
if not head:
return None
if head.val == val:
return head.next
current = head
while current.next and current.next.val != val:
current = current.next
if current.next:
current.next = current.next.next
return head
# 指针影响内存分配与释放的阐述:
# 创建链表时,每创建一个新节点,会为其分配内存空间,通过指针将节点连接起来。
# 插入节点时,先创建新节点分配内存,然后调整指针,将新节点接入链表,不会释放任何已分配内存。
# 删除节点时,通过调整指针绕过要删除的节点,原本该节点占用的内存需要手动释放(在C/C++中需手动delete,Python中有垃圾回收机制会自动回收不再被引用的对象内存),若不释放会导致内存泄漏。