C語言 連結串列排序

Rocky_Ansi發表於2016-06-25
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct node{
	int data;
	struct node* next;
}ListNode;

extern int CSort();
extern ListNode* Get_Pre();

ListNode *root = NULL;//

int main(int argc, char* argv[]){
	int  a[] = { 2, 4, 3, 59, 45, 32, 22};
	ListNode *node = NULL;
	ListNode *tmp = NULL;
	int i = 0 ;

	root = (ListNode *)malloc(sizeof(ListNode)); 

	node = root;
	for(i=0; i< sizeof a / sizeof(int);  ++i){
		//printf("a in %d\n", a[i]);
		tmp = (ListNode *)malloc(sizeof(ListNode)); 
		tmp->data = a[i];
		node->next = tmp;
	 	node = tmp;
	}
	tmp->next = NULL; // 

	CSort();

	node = root->next;
	while(node){
		printf("node->data  %d\n", node->data);
 		node = node->next;// 
	}

	node = root->next;

	//逆序;
	node = Get_Pre(node);//

	while(node){
		printf("root->data  %d\n", node->data);
 		node = node->next;// 
	}
	return 0; // 
}

int CSort(){
	ListNode *p = root->next;
	ListNode *p_pre = p->next;
	int change_value = 0;
	
	assert(root); // 

	while(p){
		p_pre = p->next;
		while(p_pre){
			if(p->data <= p_pre->data){
				;
			}else{
				change_value = p->data;
				p->data = p_pre->data;
				p_pre->data = change_value;
			}
			p_pre = p_pre->next;
		}
		p = p->next;
	}
}

ListNode* Get_Pre(ListNode* head)
{
	ListNode *pre = NULL;
	ListNode *next = NULL;
	while(head){
		next = head->next;	
		head->next = pre;
		pre = head;	
		head = next;
	}
	return pre;
}

  

相關文章