排序链表时出现分段错误

未粘贴整个代码,问题仅在于排序功能 创建,必须对链接列表的元素进行排序。

Ex>输入(列表大小的5)> 9 8 7 5 3 输出> 3 5 7 8 9

 struct node{
    int info;
    struct node *link;
 };
 struct node *START = NULL;

 void sort(){//bubble sorting using temporary variable in linked list
    int t;
    struct node *t1;
    struct node *t2;

    for(t1=START;t1!=NULL;t1=t1->link){
       for(t2=START;t2!=NULL;t2=t2->link){
          if(t2->info=t2->link->info){
              t=t2->info;
              t2->info=t2->link->info;//info contains data
              t2->link->info=t;//link contains the address of each node or link (next)
          }
       }
   }
haobeiju 回答:排序链表时出现分段错误

似乎忘记了比较运算符。

更改

if(t2->info=t2->link->info)

if(t2->info >= t2->link->info)

这是完整的工作代码:

#include "stdio.h"



struct node {
    int info;
    struct node* link;
    };
    struct node* START = NULL;

    void sort(struct node* head,size_t s)

{

//bubble sorting using temporary variable in linked list
    int t;

    struct node* t1,* t2;

while(s)
{
    t1 = head;
    t2 = t1->link;

    while (t1 != NULL && t2 != NULL)        
    {
        if (t1->info >= t2->info)
        {
            t = t1->info;
            t1->info = t2->info;//info contains data
            t2->info = t;//link contains the address of each node or link (next)
        }

        t1 = t1->link;
        t2 = t2->link;
    }

    --s;
}
}

int main()

{


// Ex > input(5 the size of list) > 9 8 7 5 3 output > 3 5 7 8 9

struct node n1,n2,n3,n4,n5;

struct node* head = &n1;

n1.info = 9;
n1.link = &n2;
n2.info = 8;
n2.link = &n3;
n3.info = 7;
n3.link = &n4;
n4.info = 5;
n4.link = &n5;
n5.info = 3;
n5.link = NULL;


while (head)
{
    printf("%d ",head->info);
    head = head->link;
}

printf("\n");

head = &n1;

sort(head,5);

while (head)
{
    printf("%d ",head->info);
    head = head->link;
}

}
本文链接:https://www.f2er.com/3147026.html

大家都在问