gpt4 book ai didi

c - 链表头始终为空

转载 作者:行者123 更新时间:2023-11-30 14:23:48 27 4
gpt4 key购买 nike

我有一个实验室作业,我们必须创建一个链接列表。我已经编写了实现此目的的方法。我希望在测试时能够打印出我的链接列表。我有一个 while 循环,应该遍历所有节点,但测试条件总是失败,我不明白为什么。我放入测试用例,看看每当我将一个节点插入列表时,新头是否为空。这是我的链接列表的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"

struct lnode {
char* word;
int count;
int line;
struct lnode* next;
};

struct lnode* head = NULL;

struct lnode* newNode(char *word, int line) {
struct lnode* tempnode;
char* new = word;
tempnode = (struct lnode *)malloc(sizeof(struct lnode));
tempnode->word = new;
tempnode->count = 1;
tempnode->line = line;
return tempnode;
}

void pushNode(struct lnode** head, struct lnode* node) {
if(head == NULL) {
head = node;
head = nodeGetNext(head);
head = NULL;
}
else {
node->next = head;
node = nodeGetNext(node);
node = head;
}
}

struct lnode* nodeGetNext(struct lnode* node) {
return node->next;
}

char* nodeGetWord(struct lnode* node) {
return node->word;
}

int main() {
struct lnode* a;
struct lnode* b;
struct lnode* c;
struct lnode* d;
struct lnode* e;
a = newNode("Hello", 0);
b = newNode("Bonjour", 1);
c = newNode("Hola", 2);
d = newNode("Bonjourno", 3);
e = newNode("Hallo", 4);
pushNode(head, a);
if(head == NULL)
printf("YES");
pushNode(head, b);
if(head == NULL)
printf("YES");
pushNode(head, c);
if(head == NULL)
printf("YES");
pushNode(head, d);
if(head == NULL)
printf("YES");
pushNode(head, e);
if(head == NULL)
printf("YES");
printList();

return 0;
}

void printList() {
printf("Hello\n");
struct lnode *currentnode;

currentnode = head;

while (currentnode != NULL) {
printf("Hello");
printf("%s:\n",nodeGetWord(currentnode));
currentnode = nodeGetNext(currentnode);
}
}

最佳答案

pushNode()中,您执行:head = NULL;head 是一个指向指针的指针...

总结一下......在下一次运行中,head 再次为 NULL......

关于c - 链表头始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12556595/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com