C语言基础学习(20)结构链表制作

mac2026-08-11  5

//** 结构链表制作 **/

#include<stdio.h> #include<string.h> #include<stdlib.h> char * s_gets(char *, int); struct film * InputIfor(struct film*); void PutIfor(struct film*); void FreeStruct(struct film *); int main() { struct film * head = NULL;//千万记得结构指针赋值 head = InputIfor(head); PutIfor(head); FreeStruct(head); return 0; } char * s_gets(char * st, int n){ char *temp; char * find; temp = fgets(st, n, stdin); if(temp){ find = strchr(st, '\n'); if(find) *find = '\0'; while(getchar() != '\n') continue; } return temp; } struct film { char names[20]; int rating; struct film * next; }; struct film * InputIfor(struct film* head) { char name[20]; struct film * current, *prev; char * st1 = "Please input a movie name:"; char * st2 = "Please input a rating of the movie:"; puts(st1); while(s_gets(name, 5) != NULL && name[0] != '\0'){ current = (struct film *)malloc(sizeof(struct film)); if(head) prev->next = current; else head = current; current->next = NULL; //head = current; printf("WAIT\n"); strcpy(current->names, name); puts(st2); scanf("%d", &current->rating); while(getchar() != '\n') continue; puts(st1); prev = current; } return head; }; void PutIfor(struct film * head) { struct film * current; if(head == NULL) printf("It is empty.\n"); else printf("There are the movie lists:\n"); current = head; while(current != NULL){ printf("The name is %s, the rating is %d \n",current->names, current->rating); current = current->next; } //return head; } void FreeStruct(struct film * head) { struct film * current; current = head; while(head != NULL) { current = head; head = current->next; free(current); } printf("Bye!\n"); }
最新回复(0)