这是一个递归的问题。我们需要编写一个函数,该函数接受链表的头节点、要插入的位置和要插入的值作为参数。如果位置为1,我们就在头部插入新节点;否则,我们递归地遍历到目标位置的前一个节点,然后在该节点的下一个节点插入新节点。
以下是Python代码示例:
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def insert(head, pos, val):
# 如果是头部插入,那么新的头节点就是新值的新节点,原头的下一个节点为新值的下一个节点
if pos == 1:
new_node = ListNode(val)
new_node.next = head
return new_node
# 如果不是头部插入,那么我们需要找到目标位置的前一个节点
current = head
for _ in range(pos - 2): # 因为是从0开始计数,所以需要减2
if current is not None:
current = current.next
else:
break
# 如果找到了目标位置的前一个节点,那么我们就在它的下一个节点插入新值的新节点
if current is not None:
new_node = ListNode(val)
new_node.next = current.next
current.next = new_node
return head
# 如果没有找到目标位置的前一个节点,那么我们就在链表的末尾插入新值的新节点
if current is None:
new_node = ListNode(val)
current = head
while current.next:
current = current.next
current.next = new_node
return head
# 测试用例
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
print("Before insertion:")
while head:
print(head.val, end=" ")
head = head.next
print()
head = insert(head, 2, 4) # 在第二个位置插入4
print("After insertion:")
while head:
print(head.val, end=" ")
head = head.next
```
这段代码首先定义了一个链表节点类,然后定义了插入函数。在插入函数中,我们首先检查是否是在头部插入。如果不是,我们遍历到目标位置的前一个节点。如果找到了目标位置的前一个节点,我们在它的下一个节点插入新值的新节点。如果没有找到目标位置的前一个节点,我们就在链表的末尾插入新值的新节点。
最后,我们通过几个测试用例来验证我们的函数是否正确。