建立一个链表,使链表中从头到尾的结点数据域依次是一个数组的各个元素的值。程序先建立链表然后再遍历输出(假定链表和数组均有6个整型元素)。
程序运行示例如下:
输入数组6个元素的值。
1 3 5 7 9 11
此链表各个结点的数据域为:1 3 5 7 9 11
#include#include #define N 6 struct LNode { int data; struct LNode *next; } ; struct LNode* create_rear(int a[], int n); void output(struct LNode *h); int main(int argc, char *argv[]) { int a[N], i; struct LNode* head; printf("输入数组%d个元素的值。n", N); for (i = 0; i < N; i++) scanf("%d", &a[i]); head = create_rear(a, N); printf("此链表各个结点的数据域为:"); output(head); return 0; } struct LNode* create_rear(int a[], int n) { struct LNode *h = NULL; struct LNode *s, *r; int i; for (i = 0; i < n; i++) { s = (struct LNode *)malloc(sizeof(struct LNode)); s->data = a[i]; s->next = NULL; if (h == NULL) h = s; else r->next = s; r = s; } return h; } void output(struct LNode *h) { struct LNode *p = h; while (p) { printf("%d ", p->data); p = p->next; //将p后移 } printf("n"); }


![[西南交通大学c语言编程题]建立一个链表,使链表中从头到尾的结点数据域依次是一个数组的各个元素的值。程序先建立链表然后再遍历输出(假定链表和数组均有6个整型元素)。 [西南交通大学c语言编程题]建立一个链表,使链表中从头到尾的结点数据域依次是一个数组的各个元素的值。程序先建立链表然后再遍历输出(假定链表和数组均有6个整型元素)。](http://www.mshxw.com/aiimages/31/665609.png)
