链表

作者:追风剑情 发布于:2020-4-20 10:49 分类:C

示例:使用链表储存用户看过的电影

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//提供malloc()原型
#include <stdlib.h>
//提供strcpy()原型
#include <string.h>
//提供CHAR_BIT的定义,CHAR_BIT表示每字节的位数
#include <limits.h>
//C99定义了bool、true、false
#include <stdbool.h>

#define TSIZE 45 //储存片名的数组大小

struct film {
	char title[TSIZE]; //影片名称
	int rating; //评级(0~10)
	struct film * next; //指向链表中的下一个结构
};

char* s_gets(char* st, int n);

int main(int argc, char* argv[])
{
	struct film * head = NULL;
	struct film * prev = NULL, *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));
		if (current == NULL)
		{
			puts("Failed to allocate memory");
			continue;
		}
		if (head == NULL) //第1个结构
			head = current;
		else
			prev->next = current;
		current->next = NULL;
		strcpy(current->title, input);
		puts("Enter your rating <0-10>:");
		scanf("%d", &current->rating);
		while (getchar() != '\n')
			continue;
		puts("Enter next movie title (empty line to stop):");
		prev = current;
	}
	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)
	{
		head = current->next;
		free(current);
		current = head;
	}
	printf("Bye!\n");

	system("pause");
	return 0;
}

// 自己实现读取函数
char* s_gets(char* st, int n)
{
	char* ret_val;
	int i = 0;
	ret_val = fgets(st, n, stdin);
	if (ret_val) //即,ret_val != NULL
	{
		while (st[i] != '\n' && st[i] != '\0')
			i++;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

运行测试

11111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号