分类: LINUX
2009-11-17 22:12:34
#include <stdio.h> |
void initList(Link *head){//初始化头结点 |
int main() { Link *head,*p; head =(Link *)malloc(sizeof(Link)); p =(Link *)malloc(sizeof(Link)); int i; int a[15]={7,4,2,7,5,8,6,3,2,4,5,7,98,3,4}; initList(head); for(i=0;i<15;i++){ addList(head,a[i]); } p = head->next; while(p->data!=65535){ printf("%d--",p->data); p = p->next; } printf("\n"); sort(head); p = head->next; while(p->data!=65535){ printf("%d--",p->data); p = p->next; } printf("\n"); } |
void sort(Link *head){ Link *p,*tmp,*flag; int max; p = (Link *)malloc(sizeof(Link)); tmp = (Link *)malloc(sizeof(Link)); flag = (Link *)malloc(sizeof(Link)); tmp = head->prior; max = tmp->data; flag = tmp; p = tmp->prior; while(p->data != 65535){//找到值最大的节点并且标记 if(p->data > max){ max = p->data; flag = p; flag->data = max; } p = p->prior; } if(flag->data!=head->next->data) {//交换最大值点到头节点后 flag->prior->next = flag->next; flag->next->prior = flag->prior; flag->next = head->next; flag->prior = head; head->next->prior = flag; head->next = flag; } while(head->prior->data != flag->data){ tmp = head->prior;//重新寻找时总是从表尾,也就是头结点的前驱开始。 p = tmp->prior; //从后往前寻找 while(p->data != flag->data){//找到要交换的节点 if(p->data > tmp->data){ tmp = p; } p = p->prior; } {//交换两个节点 tmp->prior->next = tmp->next; tmp->next->prior = tmp->prior; tmp->next = head->next; tmp->prior = head; head->next->prior = tmp; head->next = tmp; } } } |