#include
#include
#include
struct _Node {
int data;
struct _Node *next;
};
typedef struct _Node Node;
// 交换两个结点的数据
void SwapNodeData(Node *p1, Node *p2) {
int temp = p1->data;
p1->data = p2->data;
p2->data= temp;
}
// 冒泡排序对链表进行排序
void BubbleSort(Node *head) {
Node *pTemp;
int maxIdx, idx;
// 计算链表长度
maxIdx = 0;
for (pTemp = head; pTemp != NULL; pTemp = pTemp->next)
++maxIdx;
idx = 0;
while (idx < maxIdx-1) {
for (pTemp = head; idx < maxIdx-1; pTemp = pTemp->next, ++idx) {
if (pTemp->data > pTemp->next->data)
SwapNodeData(pTemp, pTemp->next);
}
idx = 0;
--maxIdx;
}
}
int main(void)
{
Node *head = NULL, *temp = NULL, *p = NULL;
int i;
srand((unsigned int)time(NULL));
// 产生随机数链表
head = (Node *)malloc(sizeof(Node));
head->data = rand() % 40;
p = head;
for (i = 1; i < 20; ++i) {
temp = (Node *)malloc(sizeof(Node));
temp->data = rand() % 40;
p->next = temp;
p = p->next;
}
p->next = NULL;
// 输出随机数链表
for (p = head; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
// 对链表排序
BubbleSort(head);
// 输出以排序的链表
for (p = head; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
// 释放资源
for (p = head->next; p != NULL; p = p->next) {
free(head);
head = p;
}
free(head);
head = NULL;
getchar();
return 0;
}
#include
#define ERROR 0
#define OVERFLOW -2
#define LIST_SIZE 20
typedef int ElemType;
typedef struct List
{
ElemType elem[LIST_SIZE];
int length;
}SqList;
int ListInsert(SqList *L,int i,ElemType e)
{
int j;
if(i<0||i>L->length+1)
return ERROR;
if(L->length>=LIST_SIZE)
return OVERFLOW;
for(j=L->length-1;j>=i-1;j--)
L->elem[j+1]=L->elem[j];
L->elem[i-1]=e;
++L->length;
}
void Union(SqList *La,SqList Lb)
{ int i,j;
ElemType e1,e2;
for(j=1;j<=Lb.length;j++)
{e2=Lb.elem[j-1];
for(i=1;i<=La->length;i++)
{e1=La->elem[i-1];
if(e1==e2)
break;
}
if(i==La->length+1)
ListInsert(La,La->length+1,e2);
}
}
void MergeList(SqList La,SqList Lb,SqList *Lc)
{
int i=1,j=1,k=0;
while(i<=La.length&&j<=Lb.length)
{
if(La.elem[i-1]<=Lb.elem[j-1])
{
ListInsert(Lc,++k,La.elem[i-1]);
++i;
}
else
{
ListInsert(Lc,++k,Lb.elem[j-1]);
++j;
}
}
while(i<=La.length)
{
ListInsert(Lc,++k,La.elem[i-1]);
i++;
}
while(j<=Lb.length)
{
ListInsert(Lc,++k,Lb.elem[j-1]);
j++;
}
Lc->length=k;
}
void print(SqList L)
{
int i;
for(i=0;i
printf("\n");
}
void main()
{
SqList La,Lb,Lc;
int j;
ElemType e;
La.length=0;
for(j=1;j<=5;j++)
{La.elem[j-1]=j;
La.length++;}
/* clrscr(); */
printf("La= ");
print(La);
Lb.length=0;
for(j=1;j<=5;j++)
{Lb.elem[j-1]=j*2;
Lb.length++;}
printf("Lb= ");
print(Lb);
Union(&La,Lb);
printf("new La= ");
print(La);
Lc.length=0;
MergeList(La,Lb,&Lc);
printf("Lc= ");
print(Lc);
}
这是个两个链表的 排序 自己整理一下 就可以出来 你 那个