1.代码如下
链表创建有多种方法,这是较好理解的一种
尾插法
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; int main(void) { int n,i,j,k; scanf("%d",&n); struct node *head,*p,*q,*t; head=NULL; while(n--) { scanf("%d",&k);//设输入2,3,5,8,9 p=(struct node *)malloc(sizeof(struct node)); p->data=k; p->next=NULL; if(head==NULL)//从if开始到下面的p=q是链表的核心思想 { head=p;//为下面输出时从头结点开始遍历做准备,第一个创建的结点,头指针指向这个结点 } else//接下来是链表的难点、、设q{2,next}, { q->next=p;//q->next={3,next} } q=p;//q={3,next};相当于q指向新设结点 } } t=head;//从头结点开始输出 while(t!=NULL) { printf("%d\t",t->data); t=t->next; } }
头插法
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; int main(void) { int n,i,j; struct node *head,*p; scanf("%d",&n); head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; for(i=0;i<n;i++) { scanf("%d",&j); p=(struct node *)malloc(sizeof(struct node)); p->data=j;///这三行相比与尾插法有较大不同,相当与是将最开始创建的结点一直往后移动 p->next=head->next;//新结点的下一个地址为空 head->next=p;创建的头结点指向新进结点 } while(p!=NULL) { printf("%d ",p->data);//头插法为逆序输出 p=p->next; } }
struct node *create(int n)//尾插和头插法另外两种实现 { int a; struct node *head,*end,*p; head=end=(struct node *)malloc(sizeof(struct node)); head->next=NULL; while(n--) { scanf("%d",&a); p=(struct node *)malloc(sizeof(struct node)); p->data=a; end->next=p;/*p->next=head->next;*/ end=p;/*head->next=p;*/ } p->next=NULL; return head;/*return end;*/ }