#include<stdio.h>#include<stdlib.h>typedefstruct linklist{int data;struct linklist *next;}node;//定义链表结构 intmain(){
node *head;
node *creat();voiddisplay(node*);
head=creat();display(head);return0;}//链表创建
node *creat(){
node *head,*p,*s;int data;printf("input a int number to start:");scanf("%d",&data);
head=(node*)malloc(sizeof(node));
s=head;while(data){
p=(node*)malloc(sizeof(node));printf("input a int number to linklist:");scanf("%d",&data);
p->data=data;
s->next=p;
s=p;}// head=head->next;
s->next=NULL;return(head);}//链表打印 voiddisplay(node *head){
node *p;
p=head->next;printf("\nChain is:");if(head!=NULL)do{printf("\n%d",p->data);
p=p->next;}while(p!=NULL);}
用头插法建立带头结点的单链表
调用malloc函数,生成一个头结点head,将head指针域置空;
调用malloc函数,建立新的节点p;
给新节点的数据域data赋值,将新节点的指针域指向head所指的节点;
将链表头结点head的指针域修改为新节点p;
重复上述步骤2~4,直至输入结束标志0尾止;`
#include<stdio.h>#include<stdlib.h>typedefstruct linklist{int data;struct linklist *next;}node;//定义链表结构 intmain(){
node *head;
node *creat();voiddisplay(node*);
head=creat();display(head);return0;}//链表创建
node *creat(){
node *head,*p;int data;printf("input a int number to linklist:");scanf("%d",&data);
head=(node*)malloc(sizeof(node));
head->next=NULL;while(data){
p=(node*)malloc(sizeof(node));
p->data=data;
p->next=head->next;
head->next=p;printf("input a int number to linklist:");scanf("%d",&data);}return(head);}//链表打印 voiddisplay(node *head){
node *p;
p=head->next;printf("\nChain is:");if(head!=NULL)do{printf("\n%d",p->data);
p=p->next;}while(p!=NULL);}