2012-09-23 63 views
0

我有一个实验室任务,我们必须创建链接列表。我已经写出了实现这一目标的方法。我希望能够在我测试它时打印出链接列表。我有一个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); 
} 
} 
+0

你试过一个调试器?逐步浏览你的代码会告诉你究竟是什么问题。 –

回答

2

pushNode()你这样做:head = NULL;head是一个指针的指针...

并包裹了这一切......就下来看,头是NULL再次.....

+0

我已经试过它的头= null注释掉,它有相同的结果 –

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] 
... 

,这表明,什么是可能是错误的。

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

+0

好的..我删除了所有的警告,我仍然得到NULL在我的测试用例的头 –

+0

修改头(而不是*头)是最大的错误......这样做,你只是修改函数堆栈中的临时变量,你不能指望列表被修改! –