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 title[TSIZE];

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 input[TSIZE];

/* Gather and store information */

puts("Enter first movie title:");

while (s_gets(input, TSIZE) != NULL && input[0] != '\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;

}

相关推荐
LL_break14 小时前
线程1——javaEE 附面题
java·开发语言·面试·java-ee
MOON404☾14 小时前
Rust 与 传统语言:现代系统编程的深度对比
开发语言·后端·python·rust
先知后行。14 小时前
Reactor模型和类图设计
java·开发语言
清欢ysy15 小时前
Cannot find module ‘@next/bundle-analyzer‘
开发语言·javascript·arcgis
伯明翰java15 小时前
mybatis-generator插件自动生成mapper及其实体模型配置
java·开发语言·mybatis
杨小码不BUG15 小时前
心痛之窗:滑动窗口算法解爱与愁的心痛(洛谷P1614)
开发语言·c++·算法·滑动窗口·csp-j/s·多维向量
froginwe1115 小时前
C# 判断语句详解
开发语言
小莞尔16 小时前
【51单片机】【protues仿真】基于51单片机智能路灯控制系统
c语言·stm32·单片机·嵌入式硬件·51单片机
無斜16 小时前
【LabVIEW实用开发】--- LabVIEW调用python脚本
开发语言·python·labview
CUMT_DJ20 小时前
matlab计算算法的运行时间
开发语言·算法·matlab