递归插入链表中的节点,给定位置和值

这是一个递归的问题。我们需要编写一个函数,该函数接受链表的头节点、要插入的位置和要插入的值作为参数。如果位置为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
```

这段代码首先定义了一个链表节点类,然后定义了插入函数。在插入函数中,我们首先检查是否是在头部插入。如果不是,我们遍历到目标位置的前一个节点。如果找到了目标位置的前一个节点,我们在它的下一个节点插入新值的新节点。如果没有找到目标位置的前一个节点,我们就在链表的末尾插入新值的新节点。

最后,我们通过几个测试用例来验证我们的函数是否正确。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值