链接列表遍历c

时间:2014-02-25 08:56:54

标签: c pointers linked-list

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);
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

您需要将start作为指针传递给add函数中的指针,以便您可以在您指定的位置完全修改它。声明应该类似于void add(int num, node** start)

此外,您应该注意在程序结束前释放为列表分配的内存。