繁体   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