#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);}