リンクリストを作成する必要があるラボの割り当てがあります。私はこれを達成するための方法を書きました。テスト時にリンクリストを印刷できるようにしたい。すべてのノードをトラバースすることになっているwhileループがありますが、テスト条件は常に失敗し、その理由がわかりません。テストケースを入れて、ノードをリストにプッシュするたびに、新しいヘッドがnullかどうかを確認します。リンクリストのコードは次のとおりです。
#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);
}
}