リンクリストを逆順で印刷するプログラムに取り組んでいます。私の再帰コードは、最後のムービーをプリントアウトしているように見えるだけです。 Microsoft Visual Studioでは「取得」が機能しないため、オンラインでコンパイルを行い、デバッガにアクセスすることはできません。期待される出力は以下の通りです。コードは以下にも掲載されています。リンクリスト、再帰
Enter first movie title:
Titanic
Enter your rating<0-10>:
5
Enter next movie title:
Inception
Enter your rating<0-10>:
8
Here is the movie list:
Movie: Titanic Rating: 8
Movie: Inception Rating: 9
Display list from tail to head:
Here is the movie list:
Movie: Inception Rating : 9
Movie: Titanic Rating : 8
実際の出力:
Here is the movie list:
Movie: Titanic Rating: 8
Movie: Inception Rating: 9
Display list from tail to head:
Here is the movie list:
Movie: Inception Rating : 9
#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
{
char title[TSIZE];
int rating;
struct film* next; /* points to next struct in list */
struct film* prev;
};
int main(void)
{
struct film *head = NULL, *prev, *current, *temp;
struct film *tail = NULL;
char input[TSIZE];
/* Gather and store information */
puts("Enter first movie title:");
while (gets(input) != NULL && input[0] != '\0')
{
current = (struct film *) malloc(sizeof(struct film)); //request a new film struct
if (head == NULL) /* first structure */
head = current;
else /* subsequent structures */
prev->next = current;
current->next = NULL;
strcpy(current->title, input);
puts("Enter your rating <0-10>:");
scanf("%d", ¤t->rating);
while (getchar() != '\n')
continue;
puts("Enter next movie title (empty line to stop):");
prev = current;
tail = current;
}
/* Show list of movies */
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;
}
puts("Display list from tail to head:");
if (tail == NULL)
puts("No data entered.");
else
puts("Here is the movie list: ");
current = tail;
while (current != NULL)
{
printf("Movie: %s Rating : %d\n", current->title, current->rating);
current = current->prev;
}
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
temp = current->next;
free(current);
current = temp;
}
return 0;
}
あなたが主張するように、あなたのプログラムには再帰はありません。 (それはそれ自身を呼び出す関数を必要とするでしょう) –
..そして、あなたはこの問題に対して全く再帰を必要としません。 –
@MichaelWalz再帰せずにどうすればいいですか? – Markovnikov