1.靜態鏈表的建立與輸出
靜態鏈表是一種比較簡單的鏈表,其所有結點都是在程序中事先定義好的,不是臨時創建的。下麵舉一個例子說明靜態鏈表的建立和輸出過程。
[例116]利用已知的三個結點建立一個靜態鏈表。
#defineNULL0
voidmain()
{
structnumber
{
intnum;
structnumber*next;
}a,b,c,*head,*p;
a.num=15;
b.num=25;
c.num=50;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;
p=head;
while(p!=NULL)
{
printf("%5d",p->num);
p=p->next;
}
}
2.動態鏈表的建立與輸出
建立動態鏈表是指從無到有地建立起一個鏈表,其結點不是在程序中定義的,而是在程序執行過程中臨時開辟的,並且要插入到鏈表中,以保持結點之間的相互鏈接關係。
[例117]編寫create函數用以創建存儲學生信息(學號、姓名)的單鏈表,以輸入學號“0”作為結束鏈表建立的標誌,再編寫print函數用以輸出學生信息,最後在main函數中調用這兩個函數,以實現動態鏈表的建立與輸出。
#defineNULL0
#defineLENsizeof(structstu)
structstu
{
intnum;
charname[10];
structstu*next;
};
structstu*create()
{
structstu*head,*new,*tail,*p;
intcount=0;
while(1)
{
new=(structstu*)malloc(LEN);
printf("inputNumberandName\n");
scanf("%d%s",&new->num,new->name);
if(new->num==0)
{
free(new);
break;
}
else
if(count==0)
{head=new;tail=new;}
else
{
tail->next=new;
tail=new;
}
count++;
}
tail->next=NULL;
return(head);
}
voidprint(structstu*head)
{structstu*p;
p=head;
if(head==NULL)
printf("listisempty\n");
else
while(p!=NULL)
{
printf("%d%s\n",p->num,p->name);
p=p->next;
}
}
voidmain()
{structstu*head;
head=create();
print(head);
}