请用c语言实现自行编写双链表的创建和输出算法 (2)新建test2-3.cpp,完成逆置算法 算法提示使用头插思想重建双链表 (3)在test2-3.cpp中编写main函数测试
时间: 2024-03-18 16:42:33 浏览: 16
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 双链表结构体
typedef struct DoubleLinkedList{
int data;
struct DoubleLinkedList *prev;
struct DoubleLinkedList *next;
} Node, *DoubleLinkedList;
// 创建双链表
DoubleLinkedList createDoubleLinkedList(int n){
DoubleLinkedList head = (DoubleLinkedList)malloc(sizeof(Node));
head->prev = NULL;
head->next = NULL;
DoubleLinkedList tail = head;
for(int i = 0; i < n; i++){
DoubleLinkedList p = (DoubleLinkedList)malloc(sizeof(Node));
p->data = i+1;
p->prev = tail;
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
// 输出双链表
void printDoubleLinkedList(DoubleLinkedList head){
DoubleLinkedList p = head->next;
while(p){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 逆置双链表
void reverseDoubleLinkedList(DoubleLinkedList head){
DoubleLinkedList p = head->next;
head->next = NULL;
while(p){
DoubleLinkedList q = p->next;
p->next = head->next;
if(head->next)
head->next->prev = p;
head->next = p;
p->prev = head;
p = q;
}
}
int main(){
// 创建双链表并输出
DoubleLinkedList head = createDoubleLinkedList(5);
printDoubleLinkedList(head);
// 逆置双链表并输出
reverseDoubleLinkedList(head);
printDoubleLinkedList(head);
return 0;
}
```
注:以上代码是标准C语言,不是C++,因此不能命名为test2-3.cpp进行编译,需要改为test2-3.c。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)