题目是:将一个顺序表里的所有数据元素以反转的方式加入到一个链表中用c语言数据结构规范写出完整程序
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct List {
Node* head;
int length;
} List;
void initList(List* list) {
list->head = NULL;
list->length = 0;
}
void addNode(List* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
}
else {
Node* p = list->head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
list->length++;
}
void reverseAdd(List* list, int* arr, int len) {
for (int i = len - 1; i >= 0; i--) {
addNode(list, arr[i]);
}
}
void printList(List* list) {
Node* p = list->head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(int);
List list;
initList(&list);
reverseAdd(&list, arr, len);
printList(&list);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bhQK 著作权归作者所有。请勿转载和采集!