6.升序降序输出
升序输出链表
#include <stdio.h>
#include <stdlib.h>
#include "mydef.h"
ElemSN * SelectSortnode(ElemSN *h);
int main()
{
int a[N] = {3,2,5,8,4,7};
ElemSN *head;
//创建单向链表
head = Createlink1(a);
//输出无序表处理后的生序链表
head = SelectSortnode(head);
printf("生序链表为:");
Printlink(head);
printf("\n");
return 0;
}
//升序输出
ElemSN * SelectSortnode(ElemSN *h)
{
ElemSN *p,*q,*pmax,*qmax,*h1 = NULL;
while(h)
{
pmax = h;
for(q = h,p = h->next; p ;q = q->next,p = p->next)
{
if(p->data > pmax->data)
{
pmax = p;
qmax = q;
}
}
if(pmax == h)
{
h = h->next;
pmax->next = h1;
h1 = pmax;
}
else
{
qmax->next = pmax->next;
pmax->next = h1;
h1 = pmax;
}
}
return h1;
}
降序输出链表
#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct node
{
int data;
struct node * next;
}ElemSN;
ElemSN * Createlink1(int a[]);
void Printlink(ElemSN *h);
ElemSN * Decnode(ElemSN *h);
int main()
{
int a[N] = {3,2,5,8,4,7};
ElemSN *head;
//创建单向链表
head = Createlink1(a);
//输出无序表处理后的降序链表
head = Decnode(head);
printf("降序链表为:");
Printlink(head);
printf("\n");
return 0;
}
ElemSN * Createlink1(int a[])
{
ElemSN *head,*tail,*p;
int i;
head = tail = (ElemSN *)malloc(sizeof(ElemSN));
head->data = a[0];
head->next = NULL;
for(i = 1;i < N;i++)
{
p = (ElemSN *)malloc(sizeof(ElemSN));
p->data = a[i];
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p = h;p != NULL;p = p->next)
{
printf("%d ",p->data);
}
}
//降序输出
ElemSN * Decnode(ElemSN *h)
{
ElemSN *p,*q,*pmin,*qmin,*h1 = NULL;
while(h)
{
pmin = h;
for(q = h,p = h->next; p ;q = q->next,p = p->next)
{
if(p->data < pmin->data)
{
pmin = p;
qmin = q;
}
}
if(pmin == h)
{
h = h->next;
pmin->next = h1;
h1 = pmin;
}
else
{
qmin->next = pmin->next;
pmin->next = h1;
h1 = pmin;
}
}
return h1;
}
合并链表
#include <stdio.h>
#include <stdlib.h>
#include "mydef.h"
ElemSN * Mergelink(ElemSN *h1,ElemSN *h2);
int main()
{
int a[N] = {2,4,6,8,10,12};
int b[N] = {1,3,5,7,9,11};
ElemSN *head1,*head2,*head;
//创建单向链表
head1 = Createlink1(a);
head2 = Createlink2(b);
//打印原链表
Printlink(head1);
printf("\n");
Printlink(head2);
printf("\n");
//输出有序链表的合并链表
head = Mergelink(head1,head2);
printf("合并链表为:");
Printlink(head);
printf("\n");
return 0;
}
//合并
ElemSN * Mergelink(ElemSN *h1,ElemSN *h2)
{
ElemSN *p,*t,*h;
h = NULL;
while(h1 && h2)
{
if(h1->data < h2->data)
{
p = h1;
h1 = h1->next;
}
else
{
p = h2;
h2 = h2->next;
}
p->next = NULL;
if(!h)
{
h = t = p;
}
else
{
t = t->next = p;
}
}
if(h1)
{
p = h1;
}
else
{
p = h2;
}
t->next = p;
return h;
}