Node Swapping in Linked List
我是C的新手,我尝试使用链表交换两个节点。不知道怎么了。它给了我一个错误的说法
"temp" is undeclared.
另外,我可以在这段代码中更改什么来交换char和int呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | struct lnode { int some_line; int count; char* some_word; struct lnode* next; }; void swapNodes(struct lnode** head, struct lnode* n1, struct lnode* n2); int main() { struct lnode* head = NULL; struct lnode* node0 = newCharNode(&head,"this is"); struct lnode* node1 = newCharNode(&head,"programming"); swapNodes(&head,node0,node1); getchar(); return 0; } void swapNodes(struct lnode** head, struct lnode* n1, struct lnode* n2) { struct lnode* current = (*head); struct lnode* temp; while((current != NULL) && (current->next != NULL)) { temp->some_word = n1->some_word; n1->some_word = n2->some_word; n2->some_word = temp->some_word; } printf("%s %s",n1,n2); current = (current->next)->next; } struct lnode* newCharNode(struct lnode** head, char* myword) { struct lnode* new_node = (struct lnode*) malloc(sizeof(struct lnode)); new_node ->some_word = myword; new_node ->next = (*head); (*head) = new_node; } |
在无效的swapnodes()中
1 | temp->some_word |
这里temp只是一个未初始化的指针,您不能进行该赋值。