0

我试图以与输入相反的顺序打印出链接列表的结果。该程序需要 3 个输入,歌曲名称、歌曲长度(以秒为单位)和版权。该程序应获取歌曲列表并以输入它们的相反顺序打印。

我对链表不太熟悉。这是我第一次将它用作某种数据库。

#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)

//defining struct
typedef struct node
{
char songName[20];
int songLength;
int copyright;
struct node * next;
}node;

//defining prototypes
node *create(int n);
void display(node *head);


int main()
{
    int n = 0;

    node *head = NULL;

    printf("How many entries?\n");
    scanf("%d", &n);

    //call to create list
    head = create(n);

    printf("\nThe linked list in order is:\n");
    display(head);

return 0;
}

node *create(int n)
{
node *head = NULL;
node *temp = NULL;
node *p = NULL;

for (int i = 0; i < n; i++)
{
    temp = (node*)malloc(sizeof(node));
    printf("What is the name of song %d\n", i + 1);
    //fgets(temp->songName, 20, stdin);
    scanf("%s", &temp->songName);

    printf("What is the length of song %d (in seconds)?\n", i + 1);
    scanf("%d", &temp->songLength);

    printf("Is song %d copyrighted?(1 = YES, 0 = NO)\n", i + 1);
    scanf("%d", &temp->copyright);

    temp->next = NULL;

    if (head == NULL)
    {
        head = temp;
    }
    else
    {
        // if not empty, attach new node at the end
        p = head;

        while (p->next != NULL)
        {
            p = p->next;
        }
        p->next = temp;
    }
}
return head;
}

void display(node *head)
{
    node *p = NULL;

    if (head == NULL)
    {
        printf("List is empty\n");
    }
    else
    {
            p = head;
        while (p != NULL)
        {
        printf("Song: %s, ", p->songName);
        printf("%d minutes, ", p->songLength);
        if (p->copyright == 1)
        {
            printf("Copyrighted\n");
        }
        else if (p->copyright == 0)
        {
            printf("No copyright\n");
        }
            p = p->next;
    }
}
}

因此,如果输入以下内容:

歌曲 1 - All Star(歌曲名称)、237(秒)、0(无版权)

歌曲 2 - Crab Rave, 193, 0

歌曲 3 - 7 环, 185, 1(版权)

输出应该是:

7 环, 185, 1

螃蟹狂欢, 193, 0

全明星, 237, 0

4

1 回答 1

4

如果您有一个(正向)链表,以相反顺序打印它的最简单方法可能是使用递归:

void display_recursive(node *n) {
    if (!n) {
      return;
    }
    display_recursive(n->next);
    printf("Song: %s, ", n->songName);
    ...
}

递归意味着一个函数正在调用自己(直到达到某个结束条件,即锚点)。这样,程序流将建立一个 display_recursive- 函数调用的“堆栈”,第一个节点,然后是第二个节点,...,直到它到达最后一个节点;到那时,递归停止,并处理 display_recursive 的打印部分,从最后一个节点向后开始。

希望这个解释有所帮助;在调试器中试一试,看看会发生什么。

于 2019-01-29T23:31:35.640 回答