我正在尝试找到一种方法来实现双向链表以及快速排序算法来对链表进行排序。到目前为止,我只是在列表上工作但是我一直遇到“分段错误”错误。有人能帮忙吗?
node.c的源代码:
#include "node.h"
#include <stdlib.h>
#include <stdio.h>
//Function to swap the nodes.
void swap(struct mynode* one, struct mynode* two){
struct mynode *result = one;
one = two;
two = result;
}
//Function to determine the final node in the list.
struct mynode *finalnode(struct mynode *root){
while(root && root->next){
root = root->next;
}
return root;
}
//Function to split the nodes.
struct mynode* partition(struct mynode* one, struct mynode *two){
const int x = two->value;
struct mynode *i = one->prev;
struct mynode *j = 1;
for(j; j != two; j = j->next){
if(j->value <= x){
i = (i == NULL) ? one : i->next;
swap(i, two);
}
}
i = (i == NULL) ? one : i->next;
swap(i, two);
return i;
}
//Function to print the list.
void printlist(struct mynode *node){
while(node){
printf("%i", node->value);
printf(" <=> ");
node = node->next;
}
printf("\n");
}
//Function to insert node.
void insert(struct mynode** node, int new_value){
struct mynode* new_node = NULL;
new_node->value = new_value;
new_node->prev = NULL;
new_node->next = (*node);
if((*node) != NULL){
(*node)->prev = new_node;
}
(*node) = new_node;
}
node.h的源代码:
#ifndef NODE_H_
#define NODE_H_
struct mynode{
int value;
struct mynode *next;
struct mynode *prev;
};
struct mynode quicksort(struct mynode*);
void printlist(struct mynode *node);
#endif
main.c的源代码:
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
void insert(struct mynode** node, int new_value);
void printlist(struct mynode *node);
int main(void){
struct mynode *test = NULL;
insert(&test, 5);
insert(&test, 10);
insert(&test, 2);
insert(&test, 4);
printf("Linked list prior to sort: ");
printlist(test);
return 0;
}
答案 0 :(得分:0)
此:
struct mynode* new_node = NULL;
new_node->value = new_value;
肯定会是段错误。您需要先分配一些内存:
struct mynode * new_node = malloc(sizeof(*new_node));