此函数用于将节点及其数据插入到链表中。
void insertNodeAndWord(struct ListNode ** pointerToHead, char word[16]) {
struct ListNode * newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode->word = word;
newNode->next = NULL;
//printf("%sn", newNode->word); // Prints out the correct words when i try to print from here.
if(*pointerToHead == NULL) {
newNode->next = *pointerToHead;
}
*pointerToHead = newNode;
}
这个功能是我从白板上获取所有单词的地方(这个功能似乎工作正常,因为当我在这里打印单词时,它会正确打印出来
struct ListNode * getAllWords(char currWord[16], int x, int y, const char board[4][4], int check[4][4], struct ListNode * list) {
if(x<0||y<0||x>=4||y>=4) { //base case
return list;
} else if (check[x][y] == 0) {
char newWord[16];
strcpy(newWord, currWord);
if(isPrefix(newWord) == 0) {
return list;
}
int length = strlen(newWord);
newWord[length] = board[x][y];
newWord[length+1] = ' ';
if(isWord(newWord) != 0) {
insertNodeAndWord(&list, newWord);
//printf("%sn", list->word); // Prints out the correct words when i try to print from here.
printf("Length: %dn", listLength(list)); // Prints out 1 every time.
}
int row, col;
for(row =-1; row<=1; row++) {
for(col=-1; col<=1; col++) {//
check[x][y] = 1; //marks the board tile as visited
getAllWords(newWord, x+row, y+col, board, check, list);
check[x][y] = 0; //unmarks the board tile as visited
}
}
}
return list;
}
struct ListNode * findWords(const char board[4][4]) {
int x, y;
int check[4][4] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
char word[16] = "";
struct ListNode * list;
list = NULL;
for(x=0; x<4; x++) {
for(y=0; y<4; y++) {
getAllWords(word, x, y, board, check, list);
// printf("%sn", list->word); // I get a "has stopped working" error here when i try to print out the words.
}
}
return list;
}
我看到的问题:
问题1
newNode->word = word;
是不对的。链表中的每个节点都将存储一个指向相同节点的指针从getAllWords
传递的存储器块。更糟糕的是内存对应于getAllWords
中的一个函数局部变量,一旦您从getAllWords
返回,该变量将不再有效。你最终会节点指向悬空内存。
你需要像这样的东西
newNode->word = strdup(word);
问题2
尚不清楚insertNodeAndWord
是否应在列表的末尾或列表的开头。
如果你想把它添加到列表的开头,你的功能可以是:
void insertNodeAndWord(struct ListNode ** pointerToHead, char word[16]) {
struct ListNode * newNode = malloc(sizeof(struct ListNode));
newNode->word = strdup(word);
newNode->next = *pointerToHead;
*pointerToHead = newNode;
}
如果要将新节点添加到列表的末尾,逻辑是更多的参与。
问题3
您没有在调用getAllWords
的地方使用它的返回值。
更改线路(在getAllWords
中(
getAllWords(newWord, x+row, y+col, board, check, list);
至
list = getAllWords(newWord, x+row, y+col, board, check, list);
更改线路(在findWords
中(
getAllWords(word, x, y, board, check, list);
至
list = getAllWords(word, x, y, board, check, list);
其他
作为一种良好的编程实践,请始终检查从malloc
返回的值。这样,就避免了取消引用NULL指针的不愉快后果。
struct ListNode * newNode = malloc(sizeof(struct ListNode));
if ( newNode == NULL )
{
// Deal with error condition.
// This is one way to deal with it - print an error message and exit.
perror("Unable to get memory for a ListNode.n");
exit(EXIT_FAILURE);
}