双链表的排序
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t{
int val;
int idx;
struct node_t *next, *prev;
}in, *in_p;
void showList( struct node_t *h )
{
printf("++++++++++++showList+++++++++++++\n");
while( h ){
printf("h->idx = %d , h->val = %d\n", h->idx, h->val );
h = h->next;
}
}
void showRList( struct node_t *h )
{
printf("+++++++++++showReverse++++++++++++++\n");
while( h->next ){
h = h->next;
}
while( h ){
printf("h->idx = %d , h->val = %d\n", h->idx, h->val );
h = h->prev;
}
}
void insertHead( struct node_t **h, struct node_t *n )
{
n->next = *h;
if( *h != NULL ){
(*h)->prev = n;
}
*h = n;
}
void insertTail( struct node_t **h, struct node_t *n )
{
if( *h == NULL ){
*h = n;
return;
}
struct node_t *p = *h;
while( p->next ){
p = p->next;
}
p->next = n;
n->prev = p;
}
in_p sort_list(in_p h){
in_p newhead = NULL, min = NULL, head = NULL;
while(h){
min = h;
head = h;
while(head->next){
if(min->val > head->next->val){
min = head->next;
}
head = head->next;
}
if(min == h){
h = h->next;
}
else{
min->prev->next = min->next;
if(min->next){
min->next->prev = min->prev;
}
}
min->next = NULL;
min->prev = NULL;
min->next = newhead;
if(newhead != NULL){
newhead->prev = min;
}
newhead = min;
}
return newhead;
}
int main()
{
int arr[] = {10,10,9,8,5,20,10,10,30,20,10,10};
struct node_t *head = NULL;
int i = 0;
struct node_t *newnode = NULL;
while( i < sizeof(arr)/sizeof(int) ){
newnode = malloc( sizeof(struct node_t) );
newnode->val = arr[i];
newnode->idx = i;
newnode->next = NULL;
newnode->prev = NULL;
insertTail( &head , newnode );
i++;
}
showList( head );
head = sort_list(head);
showList( head );
return 0;
}