用c语言编写算法逆置一个带头结点的双链表,编写双链表的创建和输出算法
时间: 2024-04-06 10:08:55 浏览: 67
双链表的创建和输出算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
struct node *prev;
} Node;
// 创建带头结点的双链表
Node* createList(int n) {
Node *head = (Node*)malloc(sizeof(Node));
head->data = -1;
head->next = NULL;
head->prev = NULL;
Node *tail = head;
int i, num;
for (i = 0; i < n; i++) {
printf("请输入第 %d 个节点的值:", i + 1);
scanf("%d", &num);
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
return head;
}
// 输出双链表
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 逆置双链表
void reverseList(Node *head) {
Node *p = head->next;
Node *q = head->next;
while (q != NULL) {
q = q->next;
p->next = p->prev;
p->prev = q;
p = q;
}
head->next->prev = NULL;
head->next = p->prev;
}
int main() {
int n;
printf("请输入双链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("原始双链表为:");
printList(head);
reverseList(head);
printf("逆置后的双链表为:");
printList(head);
return 0;
}
```
阅读全文