mysort()为直接插入排序,mysort2()为直接选择排序;
对于直接选择排序,我一开始是直接交换的结点里的数据,这个虽然是程序简单化了,但这和一个数组还有区别吗?所以我又改了交换结点,当然这就要烦的多了,一个有4种不同的情况~~~~~
- #include
- #include
- typedef structnode
- {
- int data;
- struct node*next;
- }NODE;
- NODE * mycreate()
- {
- NODE * head = NULL;
- returnhead;
- }
- NODE * myinsert(NODE *head,intdata)
- {
- 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;
- }
- returnhead;
- }
- 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;
- }
- }
- returnnewhead;
- }
- 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;
- }
- }
- returnhead;
- }
- 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);
- }
- }
- intmain()
- {
- 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;
- }