本篇目的:每次输入数据都插入到链表的头部,动态构建单链表
一、头插法原理
二、程序代码
#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);
}
程序运行结果如下: