尾插法:
头插法:
#include <stdio.h>
#include <stdlib.h>
//尾插法 & 头插法 //用数组中的元素填充结点数据域 //结点 struct linkNode{ int data; struct linkNode *next; }; void output(struct linkNode *head); //打印链表数据域 struct linkNode *creat_link_list_rear(int *a, int n); //尾插法 struct linkNode *creat_link_list_head(int *a, int n); //头插法 int main() { int a[6]; //存放结点数据 struct linkNode *head_rear; //头指针(尾插法) struct linkNode *head_head; //头指针(头插法) printf("输入数组各元素的值【6个】: "); for(int i=0; i<6; i++){ scanf("%d", &a[i]); } //尾插法 head_rear = creat_link_list_rear(a, 6); printf("此链表各个节点的数据为: "); output(head_rear); //头插法 head_head = creat_link_list_head(a, 6); printf("此链表各个节点的数据为: "); output(head_head); return 0; } //尾插法 struct linkNode *creat_link_list_rear(int a[], int n){ struct linkNode *h = NULL; //新建链表h,将每个结点依次插入到链尾,将链表的头指针返回 struct linkNode *s; //s指向要插入的结点 struct linkNode *r; //r指向链表尾结点 for(int i=0; i<n; i++){ s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = a[i]; s->next = NULL; if(h == NULL){ h = s; }else{ r->next = s; } r = s; //r指向当前链表的尾结点 } return h; //返回链表头指针 } //头插法 struct linkNode *creat_link_list_head(int a[], int n){ struct linkNode *h = NULL; struct linkNode *s; //s指向要插入的结点 for(int i=5; i>=0; i--){ s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = a[i];
s->next = NULL;
if(h == NULL){ h = s; }else{ s->next = h; h = s; } } return h; } //打印链表数据 void output(struct linkNode *head){ struct linkNode *p = head; while (p){ printf("%d ", p->data); p = p->next; } printf(" "); }