用C语言写一个程序,将一个顺序表存放在一个一维数组中的前n个数组元素位置,请编写一个顺序表的程序,将这个顺序表逆置,并输出原来顺序表和逆置后的顺序表
时间: 2024-09-24 16:31:17 浏览: 41
在C语言中,你可以创建一个结构体表示顺序表的节点,然后定义一个函数来逆置顺序表。这里是一个简单的例子:
```c
#include <stdio.h>
// 定义顺序表节点结构
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 将顺序表插入到数组
void insertToArray(Node* head, int arr[], int n) {
Node* current = head;
for (int i = 0; i < n && current != NULL; i++) {
arr[i] = current->data;
current = current->next;
}
}
// 逆置顺序表
void reverseList(Node** head) {
Node* prev = NULL;
Node* current = *head;
Node* nextTemp = NULL;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
*head = prev;
}
// 输出顺序表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
int n, data;
printf("Enter the number of elements in the list: ");
scanf("%d", &n);
int arr[n];
Node* head = NULL;
printf("Enter the elements of the list:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &data);
head = createNode(data);
if (i == 0)
head->next = NULL;
else
head->next = current;
current = head;
}
// 插入到数组并打印原始列表
insertToArray(head, arr, n);
printf("Original List (in array):");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printList(head);
printf("\n");
// 逆置顺序表并打印
reverseList(&head);
printf("Reversed List:");
printList(head);
return 0;
}
```
当你运行这个程序,它会首先询问你要输入多少个元素,然后让你逐个输入。接着,它会将顺序表存储在数组中并显示出来,再逆置顺序表后再次显示。
阅读全文