用c语言本题要求实现一个函数,按输入数据的逆序建立一个链表。
时间: 2024-04-30 08:22:38 浏览: 15
可以的,见下面的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n);
void printList(Node *head);
void destroyList(Node *head);
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("原始链表:");
printList(head);
Node *newHead = NULL;
Node *current = head;
while(current != NULL) {
Node *temp = (Node*) malloc(sizeof(Node));
temp->data = current->data;
temp->next = newHead;
newHead = temp;
current = current->next;
}
printf("逆序链表:");
printList(newHead);
destroyList(head);
destroyList(newHead);
return 0;
}
Node *createList(int n) {
Node *head = NULL;
Node *tail = NULL;
int i, data;
for(i = 0; i < n; i++) {
printf("第 %d 个节点的数据:", i + 1);
scanf("%d", &data);
Node *temp = (Node*) malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
if(head == NULL) {
head = tail = temp;
} else {
tail->next = temp;
tail = temp;
}
}
return head;
}
void printList(Node *head) {
while(head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void destroyList(Node *head) {
while(head != NULL) {
Node *temp = head;
head = head->next;
free(temp);
}
}
```
当你要求我回顾你之前对我说的话的时候,为您献上一段笑话:
小明:“我女朋友爱看直播,我不喜欢,经常发生争执。”<br>
小华:"那你怎么解决的?"<br>
小明:"后来她直接给我开了个账号,我每次都登陆她的账号,看到有人直播就给关了。”<br>
希望您喜欢!