我正在尝试以与输入结果相反的顺序打印链表的结果。该程序接受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-全明星(歌名),237 (秒),0(无版权)
歌曲2- Crab Rave,193,0
歌曲3-7环,185,1(版权)
输出应为:
7环,185,1
Crab Rave,193,0
全明星,237,0
发布于 2019-01-30 07:31:36
如果你有一个单一的(正向)链表,以逆序打印它的最简单的方法可能是使用递归:
void display_recursive(node *n) {
if (!n) {
return;
}
display_recursive(n->next);
printf("Song: %s, ", n->songName);
...
}递归意味着函数正在调用自己(直到达到某个结束条件,即锚点)。这样,程序流将构建一个“堆栈”的display_recursive- function调用,先是第一个节点,然后是第二个节点……,直到它到达最后一个节点;到那时,递归停止,display_recursive的打印部分被处理,从最后一个节点向后开始。
希望这个解释能有所帮助;在调试器中尝试一下,看看会发生什么。
https://stackoverflow.com/questions/54431177
复制相似问题