我是 C 新手。我正在尝试使用链表交换两个节点。不知道出了什么问题。它给了我一个错误,说
"temp" is undeclared.
另外,我可以在这段代码中更改什么来不仅交换 char 还交换 int ?
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;
}
最佳答案
在 void swapNodes() 中
temp->some_word
此处 temp 只是一个未初始化的指针,您无法进行该分配。
关于c - 链表中的节点交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15045398/