本篇目的:每次輸入數據都插入到鏈表的頭部,動態構建單鏈表
一、頭插法原理
二、程序代碼
#include<stdio.h>
#include<stdlib.h>
struct node* CreateNode(int x)
{//爲數據x生成一個結點
//成功後,返回指向新結點的指針
//失敗後,返回空指針
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==0)return 0;//失敗
temp->data=x;//寫入數據
temp->next=0;//防止指針懸空
return temp;
}
struct node* PushHead(struct node *head,struct node *temp)
{//把temp指向的結點
//插入到head指向的鏈表的最前面
//使得temp指向的結點成爲第一個
//成功後,返回指向新結點的指針
temp->next=head;
return temp;
}
void print_link_list(struct node *head)
{/*//打印鏈表中數據,head指向的就是數據,不帶頭結點 **/
struct node *p=head;
while(p!=0)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
int n,i,x;
struct node *head=0,*temp;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
temp=CreateNode(x);
head=PushHead(head,temp);
print_link_list(head);
}
print_link_list(head);
}
程序運行結果如下: