、编写三个函数,实现 (1)遍历一个双向链表 (2)插入一个节点 (3)删除一个节点
时间: 2024-02-02 11:02:44 浏览: 59
好的,这是一个关于编程的问题,让我来回答。
1. 遍历双向链表的函数实现:
```c++
void traverseList(Node* head) {
Node* curr = head;
while (curr != NULL) {
// 处理当前节点
curr = curr->next;
}
}
```
2. 插入节点的函数实现:
```c++
void insertNode(Node* head, Node* newNode, int index) {
if (head == NULL) {
head = newNode;
return;
}
Node* curr = head;
int i = 0;
while (curr != NULL && i < index - 1) {
curr = curr->next;
i++;
}
if (curr == NULL) {
return;
}
newNode->next = curr->next;
newNode->prev = curr;
curr->next = newNode;
if (newNode->next != NULL) {
newNode->next->prev = newNode;
}
}
```
3. 删除节点的函数实现:
```c++
void deleteNode(Node* head, int index) {
if (head == NULL) {
return;
}
Node* curr = head;
int i = 0;
while (curr != NULL && i < index - 1) {
curr = curr->next;
i++;
}
if (curr == NULL || curr->next == NULL) {
return;
}
Node* temp = curr->next;
curr->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = curr;
}
free(temp);
}
```
希望我的回答能够帮助到您!
阅读全文