有序表
有序表的归并算法
顺序表归并
单链表归并
有序表:
有序表是逻辑上的概念,是指某一种线性表,其元素的排列顺序是按元素大小递增或者是递减排列的。
有序表的归并算法:
把两个有序表的元素按某个顺序重新排列。
顺序表:
typedef int Elemtype;
typedef struct SqList
{
Elemtype data[maxsize];
int length;
}SqList;
void UnionList(SqList *L1,SqList *L2,SqList *L)
{
int j=0,i=0,k=0;//三个变量对应三个表的data域的元素下标
while (i != L1 -> length && j != L2 -> length)
{
if (L1 -> data[i] <= L2 -> data[j])
{
L -> data[k] = L1 -> data[i];
k ++; i ++;
}
else
{
L -> data[k] = L2 -> data[j];
j ++; k ++;
}
}//往L里面由小到大插入元素
while (i != L -> length)
{
L -> data[k] = L1 -> data[i];
k ++; i ++;
}
while (j != L2 -> length)
{
L -> data[k] = L2 -> data[j];
j ++; k ++;
}
L -> length = k;
}
单链表:
typedef int Elemtype;
typedef struct LinkNode
{
Elemtype data;
struct LinkNode *next;
}LinkNode;
void UnionList(LinkNode *L1,LinkNode *L2,LinkNode *L)
{
LinkNode *p1 = L1 -> next,*p2 = L2 -> next,*r = L,*s;
while (p1 != NULL && p2 != NULL)
{
if (p1 -> data <= p2 -> data)
{
s = (LinkNode *)malloc(sizeof(LinkNode));
s -> data = p1 -> data;
r -> next = s;
r = s;
p1 = p1 -> next;
}
else
{
s = (LinkNode *)malloc(sizeof(LinkNode));
s -> data = p2 -> data;
r -> next = s;
r = s;
p2 = p2 -> next;
}
}
while (p1 != NULL)
{
s = (LinkNode *)malloc(sizeof(LinkNode));
s -> data = p1 -> data;
r -> next = s;
r = s;
p1 = p1 -> next;
}
while (p2 != NULL)
{
s = (LinkNode *)malloc(sizeof(LinkNode));
s -> data = p2 -> data;
r -> next = s;
r = s;
p2 = p2 -> next;
}
r -> next = NULL;
}