0
此代碼嘗試按優先級排序一系列節點,事情是,我從函數返回來排序節點,我所做的任何事情都沒有堅持。以下是我的簡單代碼,後面跟着輸出。C結構指針作爲參數:對結構進行永久更改
#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)
您是否嘗試過調試 – 2014-10-10 01:49:05
該程序似乎顯然不完整。你將所有'next'和'prev'指針設置爲'null',然後嘗試使用它們。 – 2014-10-10 01:50:00
@GregHewgill我相信代碼試圖將'next'和'prev'鏈接到一個列表順序,根據'priority'中整數的順序排列順序 – 2014-10-10 02:03:49