您的位置:首页 > 其它

用链表实现直接选择排序和直接插入排序

2012-07-18 23:15 246 查看
mysort()为直接插入排序,mysort2()为直接选择排序;

对于直接选择排序,我一开始是直接交换的结点里的数据,这个虽然是程序简单化了,但这和一个数组还有区别吗?所以我又改了交换结点,当然这就要烦的多了,一个有4种不同的情况~~~~~

#include <stdio.h>
#include <stdlib.h>

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

NODE * mycreate()
{
NODE * head = NULL;
return head;
}

NODE * myinsert(NODE *head,int data)
{
NODE *q = head;
if(head == NULL)
{
head = (NODE *)malloc(sizeof(NODE));
head->data = data;
head->next = NULL;
}
else
{
while(q->next != NULL)
{
q = q->next;
}
NODE *newnode = (NODE *)malloc(sizeof(NODE));
newnode->data = data;
q->next = newnode;
newnode->next = NULL;
}
return head;
}

NODE * mysort(NODE *head)
{
NODE *newhead = mycreate();
NODE *q = head;
NODE * max;
NODE * tmp = NULL;
max = (NODE *)malloc(sizeof(NODE));
max->data = head->data;
NODE *maxpre = head;
while(head != NULL)
{
max->data = head->data;
q = head;
while(q->next != NULL)
{
if(q->next->data > max->data)
{
max->data = q->next->data;
tmp = q->next;
maxpre = q;
}
q = q->next;
}
newhead = myinsert(newhead,max->data);
if(tmp != NULL)
{
maxpre->next = tmp->next;
if(tmp == head)
{
head = head->next;
}
free(tmp);
tmp = NULL;
}
else
{
free(head);
head = NULL;
}
}
return newhead;
}

NODE * mysort2(NODE *head)
{
NODE *q = head;
NODE *last = head;
NODE *p = NULL;
NODE *max = NULL;
NODE *premax = NULL;
NODE *nextmax = NULL;
NODE *prelast = NULL;
NODE *lastnext = NULL;
int tmp;
while(last->next != NULL)
{
p = last;
lastnext = last->next;
max = p;
while(p->next != NULL)
{
if(p->next->data > max->data)
{
max = p->next;
premax = p;
}
p = p->next;
}
if(last == head)
{
nextmax = max->next;
if(premax == last)
{
last->next = nextmax;
max->next = last;
head = max;
}
else
{
premax->next = last;
head->next = max->next;
max->next = lastnext;
head = max;
}
last = head->next;
prelast = head;
}
else
{
nextmax = max->next;
prelast->next = max;
if(premax == last)
{
max->next = last;
last->next = nextmax;
}
else
{
premax->next = last;
last->next = nextmax;
max->next = lastnext;

}
last = prelast->next;
prelast = last;
last = last->next;
}

}
return head;
}

void myprint(NODE *head)
{
if(head == NULL)
{
printf("Empty !\n");
}
else
{
while(head->next != NULL)
{
printf("%d\t",head->data);
head = head->next;
}
printf("%d\n",head->data);
}
}
int main()
{
NODE *head = mycreate();
head = myinsert(head,1);
head = myinsert(head,2);
head = myinsert(head,3);
head = myinsert(head,4);
head = myinsert(head,5);
head = myinsert(head,6);
printf("排序前:");
myprint(head);
head = mysort2(head);
printf("排序后:");
myprint(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: