c - 链表中的节点交换

标签 c nodes

我是 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/

相关文章:

Swift - 未检测到随机碰撞

c++链表模板和节点

Java 二叉树中通用节点数组,无法创建 nil 节点

Jenkins节点连接问题

C编程: How to continue input to array from certain element

php - 使用 PHP 添加 XML 节点

c - 这个 char 数组返回未定义的行为吗?

c - 如何打印从 C 中的 scanf 输入整数开始递减的奇数?

C不能只循环一次

c - 运行互斥体,但无法创建多个线程