此代码试图按优先级排序一系列节点,事实是,我从函数返回一个节点排序,我所做的任何事情都不会持续存在。下面是我的简单代码,后面是输出。
#include <stdio.h>
#include <stdlib.h>
#define null 0
typedef struct NODE{
struct NODE * next;
struct NODE * prev;
int priority;
}NODE;
struct NODE nodes[5];
struct NODE * head = null;
NODE * function( NODE * pHead, NODE * top){
NODE * pos = top;
if(top == null){
top = pHead;
}
else{
if(top->priority < pHead->priority){
top = pHead;
pHead->prev = pos->prev;
pHead->next = pos;
pos->prev = pHead;
}
while(pHead->priority < pos->priority){
pos = pos->next;
if(pos == null){
pos->next = pHead;
pHead->prev = pos;
pHead->next = null;
return top;
}
}
(pos->prev)->next = pHead;
pHead->prev = pos->prev;
pHead->next = pos;
pos->prev = pHead;
}
return top;
}
void printNodes(){
NODE * pos = head;
while(pos != null){
printf("PRIORITY ORDER!:::::%d\n", pos->priority);
pos = pos->next;
}
}
int main(){
nodes[0].priority = 10;
nodes[1].priority = 9;
nodes[2].priority = 8;
nodes[3].priority = 7;
nodes[4].priority = 6;
nodes[0].next = null;
nodes[1].next = null;
nodes[2].next = null;
nodes[3].next = null;
nodes[4].next = null;
nodes[0].prev = null;
nodes[1].prev = null;
nodes[2].prev = null;
nodes[3].prev = null;
nodes[4].prev = null;
head = function(&nodes[0], head);
printf("HEAD %p\n", head);
printf("PRIORITY ORDER!:::::%d\n", head->priority);
head = function(&nodes[1], head);
printf("PRIORITY ORDER!:::::%d\n", head->priority);
head = function(&nodes[2], head);
printf("PRIORITY ORDER!:::::%d\n", head->priority);
head = function(&nodes[3], head);
printf("PRIORITY ORDER!:::::%d\n", head->priority);
head = function(&nodes[4], head);
printf("PRIORITY ORDER!:::::%d\n", head->priority);
printNodes();
return 0;
}
输出:
HEAD 0x600c20
PRIORITY ORDER!:::::10
Segmentation fault (core dumped)
答案 0 :(得分:2)
段错由以下原因引起:
if(pos == null){
pos->next = pHead;
取消引用空指针。
由于变量名称不一致(top
为head
且pHead
是下一个节点等),我无法关注您的代码。