有一個要求實現兩個功能我如何返回一個節點列表中的用C
directed_by(node_t * list, char * director)
rated(node_t * list, const rating_t rating)
每次都需要我通過在一個列表,並遍歷它。我是C新手,實際上我並不熟悉列表結構。有人可以幫助我瞭解如何返回一個列表,以便我可以傳遞給我的兩個函數,以便可以遍歷每個列表?
這是我的代碼到目前爲止。我想我需要在我的add_movie()
函數中返回一些東西,比如node_t,但是我不知道該怎麼做?
LIST.H
#ifndef BASICLIST_H_
#define BASICLIST_H_
typedef struct node {
void * data; /* pointer to data */
struct node * next; /* pointer to next next node */
} node_t;
int list_add(node_t ** list, void * data);
#endif
MOVIE.H
#include <stdio.h>
#ifndef MOVIE_H
#define MOVIE_H
#define SIZE_LIMIT 25
#define RATING_SIZE 6
typedef struct {
char title[SIZE_LIMIT];
char director[SIZE_LIMIT];
char rating[RATING_SIZE];
//rating_t rating;
int year;
}movie_t;
void get_movie(movie_t * movie);
void print_movie(const movie_t *m);
void print_movies(const movie_t *m);
void add_movie(movie_t movie);
#endif /* MOVIE_H */
LIST.C
#include <stdio.h>
#include <stdlib.h>
#include"basiclist.h"
int list_add(node_t ** list, void * data) {
int ret = 0;
node_t * newnode = (node_t *) malloc(sizeof(node_t));
if (newnode == NULL) {
ret = -1;
}
else {
newnode->data = data;
newnode->next = *list;
}
*list = newnode;
return ret;
}
MOVIE.C
#include <stdio.h>
#include <stdlib.h>
#include "movie.h"
#include "basiclist.h"
void print_movies(const movie_t *m) {
printf("%s\t%s\t%s\t%d\n", m->title, m->director, m->rating, m->year);
}
void add_movie(movie_t movie) {
node_t * list = NULL;
movie_t first_movie = movie;
movie_t * new_movie;
new_movie = malloc(sizeof (*new_movie));
*new_movie = first_movie;
list_add(&list, new_movie);
node_t * curr;
curr = list;
while (curr != NULL) {
print_movies(curr->data);
curr = curr->next;
}
}
MAIN.C
#include "movie.h"
#include <stdlib.h>
#include <stdio.h>
#include "basiclist.h"
int main(void) {
movie_t movie1 = {"Movie1", "Director1", "PG-13", 1900};
movie_t movie2 = {"Movie2", "Director2", "R", 1900};
movie_t movie3 = {"Movie3", "Director3", "G", 1900};
movie_t movie4 = {"Movie4", "Director4", "R", 1900};
add_movie(movie1);
add_movie(movie2);
add_movie(movie3);
add_movie(movie4);
/*undefined methods
directed_by(node_t * list, char * director)
rated(node_t * list, const rating_t rating)
*/
return 0;
}
你的get和add函數不應該返回void。 – Roecrew