0

I have a function in C that should create 3 nodes for a linked list. The problem is that the function seems to be adding an extra node and I cannot spot my error. Can someone take a look at the output and code and let me know what my error is? Can the problem be with the virtual machine compile environment? I'm compiling with the following code in a virtual machine running BackTrack Linux:

gcc link.c -o link

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DELIMITER ,

struct node {
    int data;
    struct node *next;
};

struct node* create()
{
    //define head pointers
    struct node *head = NULL;
    struct node *second = NULL;
    struct node *third = NULL;

    //allocate memory
    head = malloc(sizeof(struct node));
    second = malloc(sizeof(struct node));
    third = malloc(sizeof(struct node));

    //setup fields
    //assign links
    head->data = 15;
    head->next = second;

    second->data = 20;
    second->next = third;

    third->data = 25;
    third->next = NULL;

    return head;
}

int main(int argc, const char *argv[])
{
    int size;
    struct node *head;

    head = create();

    struct node *curr = head;

    while(curr->next != NULL)
    {
        printf("%d\n", curr->data);
        curr++;
    }

    return 0;
}

this is the output:

15 0 20 0

4

2 回答 2

1

使用链表时,curr++ 不像在标准数组中那样工作。链表的全部意义在于链表中的数据不是连续的。您不能简单地增加 curr 并期望它指向列表中的下一个元素,因为 malloc 不保证顺序调用将返回内存顺序单元的地址。

你正在寻找的是

curr = curr->next;

但是,这也需要您修改循环。由于 curr->next 将在最后一个节点之前为 NULL,因此您的最后一个元素将被跳过。你虽然条件

curr->next != NULL

经过上述调整后,应为

curr != NULL

此外, malloc 返回 void 指针,虽然没有必要,但我会说您应该将它们转换为正确的指针类型。

 //allocate memory
head = (struct node*) malloc(sizeof(struct node));
second = (struct node*) malloc(sizeof(struct node));
third = (struct node*) malloc(sizeof(struct node));
于 2013-10-21T00:35:22.190 回答
0
while(curr)
{
    printf("%d\n", curr->data);
    curr = curr->next;
}

我更喜欢做

for(curr = head; curr ; curr = curr->next)
{
    printf("%d\n", curr->data);
}
于 2013-10-21T00:34:21.850 回答