簡體   English   中英

用C語言打印鏈接列表的第一個元素

[英]Print first element of linked list in C lang

在教我如何在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);


}

親愛的朋友,在getNode函數中,您需要返回頭指針而不是當前指針。 頭指針指向第一個節點,但當前節點指向最后一個節點,因為每次執行循環時都會更新當前節點。 因此,我們需要返回頭指針才能遍歷鏈接列表或打印第一個元素。 希望你能得到它! 干杯,隨時提問

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM