gpt4 book ai didi

c - 使用双向链表排序的问题

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

我试图通过以下 C 语言方法来实现排序 - 接受整数并将它们保存到数组中。传递每个数组值并将其按升序排列在双向链表中。我已经编写了程序,但遇到了崩溃,调试说它是显示函数中的段错误,但我仍然无法弄清楚。提示将不胜感激。

#include<stdio.h>
#include<stdlib.h>

struct node //Doubly linked list to store in ascending order
{
int info;
struct node *llink; //Left link
struct node *rlink; //Right link
};

typedef struct node *NODE; //Define a custom data type for pointer to node(a structure)

/*Accept an integer argument and insert into a doubly linked list at appropriate position to arrange in ascending order*/
void list_sort(NODE head,int item)
{
NODE cur,prev,temp,prev_to_prev;
temp=malloc(sizeof(struct node)); //Allocate block of memory for a new node to be inserted
temp->info=item; //Assign the integer to info field of the node
if(head->rlink==NULL) //head->rlink==NULL when the first node is being inserted
{
head->rlink=temp;
temp->llink=head;
temp->rlink=head; //Last points to first because of circular representation used here
return;
}
cur=head->rlink;
while(cur!=head)
{
prev=cur->llink;
if(temp->info<cur->info&&temp->info>=prev->info) //when prev->info<temp->info<cur->info insert between prev and cur
{
prev->rlink=temp;
temp->llink=prev;
cur->llink=temp;
temp->rlink=cur;
return;
}
else if(temp->info>=cur->info && temp->info>prev->info) // when temp->info>cur->info and also > prev->info insert at last
{
cur->rlink=temp;
temp->llink=cur;
return;
}
else if(temp->info<cur->info && temp->info<prev->info) // when temp->info<cur->info and also < prev->info insert before them
{
prev_to_prev = prev->llink;
prev_to_prev->rlink=temp;
temp->rlink=prev;
return;
}
cur=cur->rlink;
}
}

void list_disp(NODE head)
{
NODE cur;
printf("\nSorted elements are - \n");
cur=head->rlink;
while(cur!=head)
{
printf("%d\n",cur->info);
cur=cur->rlink;
}

}

void main()
{
int items[10],i;
NODE head,cur;
head=malloc(sizeof(struct node));
head->llink=head->rlink=NULL;
head->info=0;
printf("Enter 5 items to sort: \n"); //Take only 5 items for now
for(i=0;i<5;i++)
scanf("%d",&items[i]); //Read 5 items
for(i=0;i<5;i++)
list_sort(head,items[i]); //Call function for all 5 items
list_disp(head); //Display the linked list entry by entry

}

最佳答案

一个潜在的问题是,在某些情况下您没有初始化 rlinkllink

另一个事实是您使用的是简单的赋值运算符而不是等价运算符:

temp->info>=cur->info

关于c - 使用双向链表排序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27132651/

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