节点交换链接列表

时间:2013-02-23 20:38:16

标签: c nodes

我是C的新手。我正在尝试使用链接列表交换两个节点。不确定有什么问题。它给我一个错误说

  

“temp”未声明。

另外,我可以在这段代码中更改不仅可以交换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;
  } 

1 个答案:

答案 0 :(得分:1)

在void swapNodes()

temp->some_word

这里temp只是一个未初始化的指针,你无法进行这项任务。