用数据结构实现有头结点单链表逆置输入形式:第一行输入一个整数N;第二行输入N个整数,以空格作为分隔,创建单链表;输出形式:输出逆置后的单链表,元素之间以空格分隔。样例输入5 10 20 30 40 50样例输出50 40 30 20 10
时间: 2023-05-14 18:06:38 浏览: 83
以下是用 C 语言实现有头结点单链表逆置的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createLinkedList(int n) {
LinkedList head = (LinkedList)malloc(sizeof(Node));
head->next = NULL;
Node *tail = head;
for (int i = 0; i < n; i++) {
int data;
scanf("%d", &data);
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
tail->next = node;
tail = node;
}
return head;
}
void reverseLinkedList(LinkedList head) {
Node *prev = NULL;
Node *curr = head->next;
while (curr != NULL) {
Node *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = prev;
}
void printLinkedList(LinkedList head) {
Node *curr = head->next;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
int n;
scanf("%d", &n);
LinkedList list = createLinkedList(n);
reverseLinkedList(list);
printLinkedList(list);
return 0;
}
```
如果输入样例为 "5 10 20 30 40 50",则输出样例为 "50 40 30 20 10"。
希望这个回答能够帮到你!
阅读全文