gpt4 book ai didi

c - 排序链表时出现段错误

转载 作者:行者123 更新时间:2023-11-30 16:11:02 27 4
gpt4 key购买 nike

没有粘贴整个代码,问题仅在于排序功能
创建了必须对链表中的元素进行排序的内容。

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)
}
}
}

最佳答案

似乎您忘记了比较运算符。

更改

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;
}

}

关于c - 排序链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com