在教学过程中我自己如何管理使用C链表我碰到了一些困难。我创建了一个功能getNode创建的4个整数的列表。现在我想给printf列表中的第一个元素,这样我可以学到新的东西。可惜的是,当我回想一下列表的头节点,程序打印的最后一个节点。当所有的代码是在main(),有没有问题,或者什么那么,只有当我得到因式分解提到dificulities已经发生的代码。它可能只是缺乏一个指针,或某种逻辑错误的。任何帮助apreciated!谢谢
#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);
}
我亲爱的朋友,在功能getNode你需要返回头指针不是当前的指针。在第一个节点,但在当前节点的头指针点,最后一个节点指向,因为你是在执行循环更新当前节点每次。因此,我们需要以遍历链表或打印的第一个元素返回头指针。希望你得到它!欢呼声中,随意问的问题