编写三个函数,实现 (1)遍历一个双向链表 (2)插入一个节点 (3)删除一个节点
时间: 2024-02-05 14:02:37 浏览: 72
很高兴回答你的问题!以下是对应的三个函数:
1. 遍历双向链表函数:
```c
void traverseList(Node* head) {
Node* curr = head;
while (curr != NULL) {
// 打印当前节点的值
printf("%d ", curr->val);
curr = curr->next;
}
}
```
2. 插入节点函数:
```c
void insertNode(Node** head, int val) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = val;
newNode->prev = NULL;
newNode->next = *head;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
}
```
3. 删除节点函数:
```c
void deleteNode(Node** head, Node* nodeToDelete) {
if (*head == NULL || nodeToDelete == NULL) {
return;
}
if (*head == nodeToDelete) {
*head = nodeToDelete->next;
}
if (nodeToDelete->next != NULL) {
nodeToDelete->next->prev = nodeToDelete->prev;
}
if (nodeToDelete->prev != NULL) {
nodeToDelete->prev->next = nodeToDelete->next;
}
free(nodeToDelete);
}
```
希望这些函数能够帮到你!接下来请问您还有什么问题吗?
阅读全文