只有刻意练习递归,才能掌握递归-递归专题12-头插法建立带头结点的单链表

 每来一个数据,生成一个结点,插入到链表的头部。

#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 *head,int n)
{//头插法,递归法
	if(n==0)
	{
		return;
	}
	int x;
	scanf("%d",&x);
	struct node *temp=CreateNode(x);
	temp->next=head->next;
	head->next=temp;
	createLinkList(head,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);
}

猜你喜欢

转载自blog.csdn.net/weixin_43917370/article/details/106867349