C Primer Plus(第六版)17.12 编程练习 第1题 第一种方法

/* films2.c -- using a linked list of structures */

#include <stdio.h>

#include <stdlib.h> /* has the malloc prototype */

#include <string.h> /* has the strcpy prototype */

#define TSIZE 45 /* size of array to hold title */

struct film {

struct film * last; /* points to last struct in list */

char titleTSIZE;

int rating;

struct film * next; /* points to next struct in list */

};

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

int main(void)

{

struct film * head = NULL;

struct film * end = NULL;

struct film * prev, * current;

char inputTSIZE;

/* Gather and store information */

puts("Enter first movie title:");

while (s_gets(input, TSIZE) != NULL && input0 != '\0')

{

current = (struct film *) malloc(sizeof(struct film));

if (head == NULL) /* first structure */

{

head = current;

head->last = NULL;

}

else /* subsequent structures */

{

prev->next = current;

current->last = prev;

}

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;

end = current;

}

/* Show list of movies */

if (head == NULL)

printf("No data entered. ");

else

printf ("Here is the movie Positive sequence list:\n");

current = head;

while (current != NULL)

{

printf("Movie: %s Rating: %d\n",

current->title, current->rating);

current = current->next;

}

if (head == NULL)

printf("No data entered. ");

else

printf ("Here is the movie inverted sequence list:\n");

current = end;

while (current != NULL)

{

printf("Movie: %s Rating: %d\n",

current->title, current->rating);

current = current->last;

}

/* Program done, so free allocated memory */

current = head;

while (current != NULL)

{

free(current);

current = current->next;

}

printf("Bye!\n");

return 0;

}

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'); // look for newline

if (find) // if the address is not NULL,

*find = '\0'; // place a null character there

else

while (getchar() != '\n')

continue; // dispose of rest of line

}

return ret_val;

}

相关推荐
脱胎换骨-军哥36 分钟前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
枕星而眠1 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
geats人山人海2 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
爱吃牛肉的大老虎2 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
bbq粉刷匠2 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法
影视飓风TIM3 小时前
Linux下C语言缓冲区原理 + Git版本控制
linux·c语言·git
@三十一Y3 小时前
C++:红黑树的实现
开发语言·c++
乐观勇敢坚强的老彭3 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶3 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
a1117764 小时前
中文优先的企业 RAG 知识库 开源项目
开发语言·开源·kotlin