首页 > 解决方案 > 在c中对链表一一排序

问题描述

所以,我正在尝试对我的链接列表进行排序,但是似乎存在一些问题。所以基本上我的清单是这样的

3 6 9 7
5 3 4 6
2 4 1 6

我想对第二条垂直线进行排序。升序排序后的第二行应该是这样的

5 3 4 6
2 4 1 6
3 6 9 7

但是我的代码只对第二条垂直线进行排序,并且由于某种原因不会更改其他行,我该如何解决这个问题?

3 3 9 7
5 4 4 6
2 6 1 6

这是我的排序代码

void sort(struct node **h)
{
    int i,j,a;

    struct node *temp1;
    struct node *temp2;

    for(temp1=*h;temp1!=NULL;temp1=temp1->next)
      {
        for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
          { 
            if(temp2->num1 < temp1->num1)
              {
                a = temp1->num1;
                temp1->num1 = temp2->num1;
                temp2->num1 = a;
              }
           }
       }
}

这也是我的打印功能

void printList(struct node *list) {

   //start from the beginning
   while(list != NULL) {    
      printf(" %d %d %d %d  \n",list->data, list->num1,list->num2, list->num3);
      list = list->next;
   }

}

标签: csortinglinked-list

解决方案


有两种方法可以交换链表中的项目。

  • 保留节点但替换所有数据
  • 在指针本身之间交换

在您的解决方案中,您尝试交换数据,但只更改了结构的一个成员。您需要对 、 和 执行相同datanum2操作num3


推荐阅读