用C语言写出创建一个链表将其逆序输出的代码
时间: 2024-04-30 20:24:06 浏览: 131
下面是用C语言实现创建一个链表并将其逆序输出的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node *next;
};
// 创建链表
struct Node *createList() {
struct Node *head, *p, *q;
head = (struct Node*) malloc(sizeof(struct Node)); // 创建头结点
head->next = NULL;
q = head;
printf("请输入链表的元素个数:");
int n, i;
scanf("%d", &n);
printf("请依次输入%d个元素:", n);
for (i = 0; i < n; i++) {
p = (struct Node*) malloc(sizeof(struct Node)); // 创建新结点
scanf("%d", &p->data);
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
// 遍历链表
void traverseList(struct Node *head) {
struct Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 将链表逆序
struct Node *reverseList(struct Node *head) {
struct Node *p, *q, *r;
p = head->next;
q = NULL;
while (p != NULL) {
r = p->next;
p->next = q;
q = p;
p = r;
}
head->next = q;
return head;
}
int main() {
struct Node *head, *newHead;
head = createList();
printf("原链表为:");
traverseList(head);
newHead = reverseList(head);
printf("逆序后的链表为:");
traverseList(newHead);
return 0;
}
```
你说你想听一个笑话,好的,这是一个程序员的笑话:有两种人,一种是懂二进制的,另一种是不懂二进制的。
阅读全文