您的位置:首页 > 理论基础 > 数据结构算法

数据结构整理_有序顺序表合并

2015-05-20 23:24 274 查看
整理了一下顺序表的合并,挺简单的算法。用的VC++6.0整理代码!

// 整理_有序顺序表合并.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdlib.h>

#define INIT_LEN 30
#define ELEM_LEN 60

typedef int ElementType;
typedef struct SeqList
{
ElementType *data;
int len;
int cap;
}SeqList;

void Merge(SeqList la, SeqList lb, SeqList *lc);
void InitList(SeqList *p);
void Create(SeqList *p, ElementType data[], int n);
void Destroy(SeqList *p);

int main(int argc, char* argv[])
{
SeqList la, lb, lc;
ElementType a[] = {1, 3, 7, 9, 12, 17, 22, 89, 99, 123};
ElementType b[] = {3,7,13,25,56,999};

Create(&la, a, sizeof(a)/sizeof(a[0]));
Create(&lb, b, sizeof(b)/sizeof(b[0]));
InitList(&lc);
Merge(la, lb, &lc);
Destroy(&la);
Destroy(&lb);
Destroy(&lc);

return 0;
}

void Merge(SeqList la, SeqList lb, SeqList *lc)
{
int i = 0, j = 0, k = 0;

while(i<la.len && j<lb.len)
{
if(la.data[i] <= lb.data[j])
{
lc->data[k++] = la.data[i++];
}
else
{
lc->data[k++] = lb.data[j++];
}
}
while(i<la.len)
{
lc->data[k++] = la.data[i++];
}
while(j<lb.len)
{
lc->data[k++] = lb.data[j++];
}
lc->len = k;
}

void InitList(SeqList *p)
{
p->data = (ElementType *)malloc(sizeof(ElementType) * INIT_LEN);
p->len = 0;
p->cap = INIT_LEN;
}

void Create(SeqList *p, ElementType data[], int n)
{
int i = 0;

InitList(p);
for(i=0; i<n; i++)
{
p->data[i] = data[i];
}
p->len = n;
}

void Destroy(SeqList *p)
{
free(p->data);
p->len = 0;
p->cap = 0;
}
如果读者发现代码有错,请务必告知于我!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: