所以我试图在C中对一个双向链表进行冒泡排序。我希望交换整个节点而不仅仅是每个节点内的元素。但是,当内循环即将停止时,我会遇到分段错误。我甚至在纸上画了我的代码,但我仍然无法弄清楚它有什么问题。下面是我的排序功能。
typedef struct list{
char letter;
double probability;
struct list* previous;
struct list* next;
}List;
void sort(int n){
int i, j;
struct list *nxt, *current;
if (current==NULL){
return;
}
for(i=0;i<n;i++){
current = head;
for(j=0;j<n-1-i;j++){
nxt = current->next;
if (current->probability<nxt->probability){
if(current->previous!=NULL){
current->previous->next=nxt;
}
if(nxt->next!=NULL){
nxt->next->previous=current;
}
current->next=nxt->next;
nxt->next=current;
nxt->previous=current->previous;
current->previous= nxt;
nxt->previous->next=nxt;
current->next->previous=current;
printf("swapped\n");
}
current = current->next;
}
}
}
答案 0 :(得分:-2)
尝试更简单地编写代码:
@WebMvcTest
我认为您的错误与行 ...
if (current->probability<nxt->probability){
struct list *prev = current->previous;
struct list *next_next = nxt->next;
swap(current, next);
current->previous = prev;
current->next = next;
next->previous = current;
next->next = next_next;
if (prev != NULL) {
prev->next = current;
}
if (next_next != NULL) {
next_next->previous = next;
}
printf("swapped\n");
}
current = current->next;
...
有关,因为如果您交换元素,则应使用current = current->next
。
函数交换可能如下所示:
current->next->next