簡體   English   中英

C中的鏈表遍歷

[英]Linked list traversing in c

main函數中,我創建一個n = 50且next = NULL的節點。 當我在鏈接列表中add 10時,盡管已經添加了它,但是在遍歷時它不會顯示。 發生這種情況的原因是,在調用add函數時,指向具有50的節點的start指針未更新為指向具有10的新節點。 (第28行到第34行)。

#include <stdio.h>    
#include <stdlib.h>

typedef struct node
{
    int n;
    struct node* next;
} node;

void traverse(node* start)
{
    while(true)
    {
        printf("%i\n",start->n);
        start = start->next;
        if(start == NULL)
        {
            break;
        }
    }
}

void add(int num, node* start)
{
    node* previous = NULL;
    node* current = start;
    if(num<current->n)
    {
 //------------------------------------------------------------------------------

        //The problem is inside this if block.
        node* tmp = malloc(sizeof(node));
        tmp->next = current;
        current = tmp;
//-------------------------------------------------------------------------------

    }
    else
    {
        while(true)
        {
            previous = current;
            current = current->next;
            if(current == NULL)
            {
                node *tmp = malloc(sizeof(node));
                tmp->n = num;
                tmp->next = NULL;
                previous->next = tmp;
                break;
            }
            else
            {
                if(current->n > num)
                {
                    node *tmp = malloc(sizeof(node));
                    tmp->n = num;
                    tmp->next = current;
                    previous->next = tmp;
                    break;
                }
            }
        }
    }
}
int main(void)
{
    node* start = malloc(sizeof(node));
    start->n = 50;
    start->next = NULL;
    add(10,start);
    traverse(start);
}

我怎么解決這個問題?

您需要在add函數中將start作為指針傳遞給指針,以便您可以在指定的位置准確地對其進行修改。 聲明應類似於void add(int num, node** start)

另外,在程序結束之前,您應注意釋放為列表分配的內存。

暫無
暫無

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

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