每来一个数据,生成一个结点,插入点链表的尾部。
所以问题的关键在于保存链表中最后一个结点的指针p,这样在其后面插入才方便。
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
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;
}
void print_link_list(struct node *head)
{/*//打印链表中数据,head指向头结点 **/
struct node *p=head->next;
while(p!=0)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void createLinkList(struct node *tail,int n)
{//尾插法,递归法
//tail指向最后一个结点
//开始时tail指向头结点
if(n==0)
{
return;
}
int x;
scanf("%d",&x);
struct node *temp=CreateNode(x);
temp->next=tail->next;
tail->next=temp;
createLinkList(temp,n-1);
}
int main()
{
int n,i,x;
struct node head,*temp;
head.next=0;
scanf("%d",&n);
createLinkList(&head,n);
print_link_list(&head);
}