初学C语言4.2-单链表,头插入,尾插入

函数快查------https://fishc.com.cn/thread-66397-1-1.html
单链表

头插入举例

#include<stdio.h>

struct Book
{
    char title[128];
    char author[40];
    struct Book *next;//指针域 
};//结构体 

void getInput(struct Book *book)
{
	printf("请输入书名:");
	scanf("%s",book->title); 
	
	printf("请输入作者:");
	scanf("%s",book->author);
}//定义getinput 


void addBook(struct Book **library)
{
	struct Book *book,*temp;//temp为临时地址,存放插入节点后面的信息域 
	
	book = (struct Book *)malloc(sizeof(struct Book));
	//申请一块内存空间 
	if(book == NULL){
		printf("内存分配失败\n");
		exit(1);
	} 
	getInput(book);//传入函数*book的地址 
	
	if(*library != NULL)
	{
		temp = *library;
		*library = book;
		book->next = temp; 
		//插入  
	}
	else
	{
		*library = book;
		book->next = NULL;
	}
}
void printLibrary(struct Book *library)
{
	struct Book *book;
	int count = 1;
	
	book = library;
	while(book != NULL)
	{
		printf("Book%d \n",count);
		printf("书名:%s\n",book->title);
		printf("作者:%s\n",book->author);	
		book = book->next;
		count++;
	}
}

void releaseLibrary(struct Book *library)
    {
    struct Book *temp; 
	
     while(library != NULL)
    {
          temp = *library;
          *library = (*library)->next;
          free(temp);
	}
}
int main(void)
{	

	struct Book *library = NULL;
	//头指针 
	 
	int ch; 

	while(1)
	{
		printf("请问是否需要录入书籍信息(Y/N)\n");
		do{
			ch = getchar();
			
		} while(ch != 'Y' && ch != 'N');//如果不是Y或N就不停循环 
		if(ch == 'Y') 
		{
			addBook(&library);
		}
		else
		{
			break;
		}
	} 
	
	printf("请问是否需要打印书籍信息(Y/N)\n");
	do
	{
			ch = getchar();
	} while(ch != 'Y' &&ch != 'N');
	if(ch == 'Y') 
	{
		printLibrary(library);
	}
	
	releaseLibrary(&library);//释放library 
	
	return 0;
 } 

尾插入,只需将addbook的头插入替换成尾插入即可

void addBook(struct Book **library)
{
	struct Book *book;
    static struct Book *tail;
    //定义指向尾部的静态指针变量 
	
	book = (struct Book *)malloc(sizeof(struct Book));
	//申请一块内存空间 
	if(book == NULL){
		printf("内存分配失败\n");
		exit(1);
	} 
	getInput(book);//传入函数*book的地址 
	
	if(*library != NULL)
	{
          tail->next = book;
          book->next = NULL;
          //插入数据
	}
	else
	{
		*library = book;
		book->next = NULL;
	}
 tail = book;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值