链表头总是空的

时间:2012-09-23 21:55:49

标签: c linked-list

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

2 个答案:

答案 0 :(得分:2)

你在pushNode()中执行了{p> head = NULL;head是指向指针的指针......

并且把它全部包起来...在下一次运行中,head再次为NULL .....

答案 1 :(得分:0)

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

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(而不是它指向的内存)将产生很小的影响......(提示,提示!)

相关问题