用C语言打印链接列表的第一个元素

时间:2019-02-10 22:45:37

标签: c linked-list

在教我如何在C中管理链表时,遇到了一些困难。我创建了一个功能getNode来创建4个整数的列表。现在,我想将列表的第一个元素打印出来,以便我可以学习新的东西。不幸的是,当我尝试重新调用列表的头节点时,程序将打印最后一个节点。当所有代码都在main()中时,就没有任何问题或什么问题,只有当我将代码分解为因子时,才会出现提到的麻烦。它可能只是缺少指针或某种逻辑错误。任何帮助赞赏!谢谢

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct list
{
    int x;
    struct list *next;
}list;
list *getNode()
{
    int marker = 0;
    int base;
    list *head, *current;
    head=current=NULL;
    while (marker < 4)
    {
        printf("wprowdz liczbe dla NodE o markerze: %d  \n", marker + 1);
        scanf("%d", &base);
        list *node = malloc(sizeof(list));
        node->x = base;
        node->next = NULL;
        if (head == NULL)
        {
            current = head = node;
        }
        else
        {
            current = current->next = node;
        }
        marker++;
    }
    return current;
}
void printNode(list *head)
{
    printf("this shoud print the first element of linked list :");
    printf("%d", head->x);
}
int main()
{
    list *start = getNode();
    printNode(start);


}

1 个答案:

答案 0 :(得分:0)

亲爱的朋友,在getNode函数中,您需要返回头部指针而不是当前指针。头指针指向第一个节点,但当前节点指向最后一个节点,因为每次执行循环时都会更新当前节点。 因此,我们需要返回头指针才能遍历链接列表或打印第一个元素。希望你能得到它!干杯,随时提问