【问题标题】:Linked List Head Is Always Null [closed]链表头始终为空 [关闭]
【发布时间】:2012-09-15 09:57:22
【问题描述】:

我有一个实验任务,我们必须创建一个链接列表。我已经编写了实现此目的的方法。我希望能够在测试时打印出我的链表。我有一个应该遍历所有节点的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);
}
}

【问题讨论】:

  • 你试过调试器吗?单步执行您的代码将向您确切显示问题所在。

标签: c linked-list


【解决方案1】:

pushNode() 中,您可以:head = NULL;head 是指向指针的指针...

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

【讨论】:

  • 我已经尝试过将 head = null 注释掉,结果相同
【解决方案2】:

我不会破坏正确答案(看起来像作业......?) 但是这里有一个提示:这些消息是由编译器给出的:

prova.c:31:10: warning: assignment from incompatible pointer type [enabled by default]<br>
prova.c:32:5: warning: passing argument 1 of ‘nodeGetNext’ from incompatible pointer type [enabled  by default]<br>
prova.c:25:15: note: expected ‘struct lnode *’ but argument is of type ‘struct lnode **’
prova.c:32:10: warning: assignment from incompatible pointer type [enabled by default]<br>
prova.c:36:16: warning: assignment from incompatible pointer type [enabled by default]<br>
prova.c:38:10: warning: assignment from incompatible pointer type [enabled by default]
...

这表明可能有问题。

此外,修改函数参数head(而不是它指向的内存)将没有什么效果......(提示,提示!)

【讨论】:

  • 好吧..我删除了所有的警告,但在我的测试用例中仍然得到 NULL
  • 修改head(而不是*head)是最大的错误......这样做你只是修改了函数堆栈中的一个临时变量,你不能指望修改列表!
猜你喜欢
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2021-11-04
  • 2017-02-06
  • 2022-01-20
相关资源
最近更新 更多