簡體   English   中英

如何顛倒鏈表的順序?

[英]How can I reverse the order of a linked list?

我試圖以與輸入相反的順序打印出鏈表的結果。該程序需要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

螃蟹狂歡,193,0

全明星,237,0

如果您有一個(正向)鏈接列表,則以相反的順序打印它的最簡單方法是使用遞歸:

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

遞歸表示函數正在調用自身(直到達到某種結束條件,即錨點)。 通過這種方式,程序流程將建立一個display_recursive-函數調用的“堆棧”,其中第一個節點,然后是第二個節點,直到到達最后一個節點為止。 到那時,遞歸停止,從最后一個節點向后開始處理display_recursive的打印部分。

希望這種解釋有所幫助; 在調試器中嘗試一下,看看會發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM