用C语言编程:将一个链表按逆序排列,即将链头当链尾,链尾当链头。 程序的运行示例如下: 请输入链表(非数表示结束) 结点值:3 结点值:4 结点值:5 结点值:6 结点值:7 结点值:end 原来表: 3 4 5 6 7 反转表: 7 6 5 4 3
时间: 2023-12-28 07:04:06 浏览: 203
以下是一份使用C语言编写的链表逆序排列程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
Node* reverseList(Node* head) {
Node *prev = NULL, *current = head, *next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
Node* current = NULL;
int value;
printf("请输入链表(非数表示结束)\n");
while (scanf("%d", &value) == 1) {
if (value == -1) break;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = head;
} else {
current->next = newNode;
current = current->next;
}
}
printf("原来表: ");
printList(head);
head = reverseList(head);
printf("反转表: ");
printList(head);
return 0;
}
```
程序会要求用户输入链表节点的值,当输入一个非数值时,程序会认为输入结束。程序会首先根据用户的输入创建链表,然后调用 `reverseList` 函数将链表逆序排列,最后输出结果。
阅读全文
相关推荐














