编写一个函数,实现在链表中给定位置插入,删除的结果链表
时间: 2023-05-11 22:07:00 浏览: 74
非常好,这是一个编程类的问题,我可以回答。以下是一个示例代码,可以实现在链表中给定位置插入和删除节点的功能:
```
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 在链表中给定位置插入节点
ListNode* insertNode(ListNode* head, int pos, int val) {
ListNode* newNode = new ListNode(val);
if (pos == 0) {
newNode->next = head;
return newNode;
}
ListNode* cur = head;
for (int i = 0; i < pos - 1; i++) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
return head;
}
// 在链表中给定位置删除节点
ListNode* deleteNode(ListNode* head, int pos) {
if (pos == 0) {
return head->next;
}
ListNode* cur = head;
for (int i = 0; i < pos - 1; i++) {
cur = cur->next;
}
cur->next = cur->next->next;
return head;
}
```
以上代码中,insertNode函数可以在链表的任意位置插入一个新节点,deleteNode函数可以在链表的任意位置删除一个节点。需要注意的是,链表的位置从0开始计数。