尝试在 C 中打印链表节点 - 仅打印最后一个节点?

Trying to Printf Linked List nodes in C - prints only last node?

我有一个节点的简单链表数组。

我在列表中插入了一堆元素

printList() 中,while 循环只是无限地打印列表中的最后一个节点。但是为什么??

逻辑错了吗?我要求只要 head 值不为 NULL 就打印?我已经尝试在创建时打印下一个节点,它会打印出来。但由于某种原因,该功能不起作用。任何想法

    #include <stdio.h>
#include <stdlib.h>

typedef struct process
{
    int data;
    int burst;
    struct process *next;
} node;

node *head = NULL;

void insert(int data, int burst);
void printList();

int main()
{

    insert(1, 100);
    insert(2, 200);
    insert(3, 300);
    insert(4, 400);
    printList();

    return 0;
}

void insert(int data, int burst)
{
    node *temp = (node *)malloc(sizeof(node));

    if (head == NULL)
    {
        temp->data = data;
        temp->burst = burst;
        temp->next = NULL;

        head = temp;
        // printf("\n\n Head = %d burst = %d\n", head->data, head->burst);
    }
    else
    {
        // // ref the first element
        temp = head;
        // // change the head with the new element data
        head->data = data;
        head->burst = burst;
        head->next = temp; /* add the prev first element to the next */

        // printf("\n Next = data = %d burst = %d\n", temp->data, temp->burst);
    }
}

void printList()
{
    printf("printing...");

    // print the rest elements
    while (head != NULL)
    {
        printf("\nNext = %d  burst = %d\n", head->data, head->burst);
        head = head->next;

    }
}

因为你的插入有误。 temp = head ?您刚刚泄露了您分配的节点,然后 head->next = temp 指向 "next" 到 "self".

插入函数中的这段代码

else
{
    // // ref the first element
    temp = head;
    // // change the head with the new element data
    head->data = data;
    head->burst = burst;
    head->next = temp; /* add the prev first element to the next */

    // printf("\n Next = data = %d burst = %d\n", temp->data, temp->burst);
}

没有意义并且有内存泄漏,因为分配内存的地址被分配给了指针temp

node *temp = (node *)malloc(sizeof(node));

然后指针的值被覆盖

    temp = head;

所以分配内存的地址丢失了

按如下方式重写函数

void insert(int data, int burst)
{
    node *temp = (node *)malloc(sizeof(node));

    temp->data = data;
    temp->burst = burst;
    temp->next = head;

    head = temp;
}

如果函数将 return 一个表示新节点的内存分配是否成功的值,那就更好了。

例如

int insert(int data, int burst)
{
    node *temp = (node *)malloc(sizeof(node));
    int success = temp != NULL;

    if ( success )
    { 
        temp->data = data;
        temp->burst = burst;
        temp->next = head;

        head = temp;
    }

    return success;
}

函数printList也不正确,因为它改变了全局变量head。你应该引入一个中间变量而不是使用 head.

void printList()
{
    printf("printing...");

    // print the rest elements
    for ( node *current = head; current != NULL; current = current->next )
    {
        printf("\nNext = %d  burst = %d\n", current->data, current->burst);
    }
}

考虑到函数依赖于全局变量是个坏主意。例如,您无法在一个程序中使用两个列表。