The first real list!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TSIZE 45
struct film{
	char title[TSIZE];
	int rating;
	struct film * next;
};
char * s_gets(char * st, int n)
{
	char * ret_val;
	char * find;
	
	ret_val = fgets(st,n,stdin);
	if(ret_val){
		find=strchr(st,'\n');
		if(find)
			*find='\0';
		else
			while(getchar()!='\n')
			continue;
	}
	return ret_val;
}
int main()
{
	struct film * head=NULL;
	struct film * prev,*current;
	char input[TSIZE];
	puts("Enter first movie title:");
	while(s_gets(input,TSIZE)!=NULL&&input[0]!='\0')
	{
		current=(struct film *) malloc(sizeof(struct film));//malloc返回的是void指针,强转为结构体型指针并将已经分配好的空间的指针返回给current 
		if(head==NULL)//如果头指针为空,也就是处理第一项时 
			head=current;//将 空间的指针给head,并开始给head结构成员赋值 
		else
			prev->next=current;
		current->next=NULL;//初始化current的next指针 
		strcpy(current->title,input);//后复制给前,将已输入的title信息赋值给current.title 
		puts("enter your rating<0-10>:");//
		scanf("%d",¤t->rating);
		while(getchar()!='\n')
			continue;
		puts("Enter next movie title(empty line to stop):");
		prev=current;
	}
	//整个处理流程:
	/*0.输入title并判断是否为空,为空则退出 
	1.current去开辟一块存结构体的空间并作为空间的指针
	2.如果是处理头指针则将空间的地址赋给头指针,如果不是,则将地址赋给prev的next 
	3.将current的next赋值为NULL
	4.将本次输入的title赋值给current的title
	5.输入rating并直接赋值给current的rating 
	6.处理溢出数据 
	7.将current赋值给prev 
	*/
	
	
	//以下是输出电影信息的代码 
	if(head == NULL)
		printf("NO data entered.");
	else
		printf("Here is the movie list:\n");
	current=head;
	while(current != NULL)
	{
		printf("Movie: %s Rating: %d\n",current->title,current->rating);
		current = current ->next;
	}
	
	//以下是电影输出完毕并释放内存的代码
	current=head;
	while(current != NULL)
	{
		free(current);//这条语句 
		current=current->next;
	 } 
	 printf("Bye!\n");

	 return 0;
}

人生中第一个真正的链表程序,虽然是cpp上抄的吧,最后的那个循环里还出个bug

本来是head=current->next,死循环了,应该是current=current->next,要不然判断框里变量就没变,真的蠢····

输入函数的解释在另外一个list博客里

最核心的东西其实就是这个current,它是一个struct film * 在记录时,current去开辟内存,然后记录地址,把地址给头指针,然后改变current里的成员变量时,其实就是改变了节点里的成员变量,因为他们指向同一个地址了,改变以后就把current赋值给prev等到下一轮循环的时候,将新的current地址赋值给prev->next,所以就链接起来了。


再等到输出和释放内存的时候,流程都是一样的,将头指针赋值给current, 然后current=current->next开始一个一个的处理就行了。


虽然这个程序抄来的,但是真的是研究了大概一个星期,恩,慢是慢了点,但是通过这个程序

我学会了结构体指针(第一次用指针就是结构体指针真的曰狗!!!)

malloc和free的动态分配内存

链表的实现方法

还有s_gets里面的一堆知识,恩,还是不错了,偷笑一会,学链表函数去~~~

猜你喜欢

转载自blog.csdn.net/qq_41660465/article/details/79713426
今日推荐