归纳编程学习的感悟,
记录奋斗路上的点滴,
希望能帮到一样刻苦的你!
如有不足欢迎指正!
共同学习交流!
🌎欢迎各位→点赞 👍+ 收藏⭐ + 留言📝
既然选择了远方,当不负青春,砥砺前行!
将两个有序的线性表合并为一个有序的线性表
main.cpp文件
cpp
//将两个有序的线性表合并为一个有序的线性表
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"SeqList.h"
void MergeList(SeqList A, SeqList B, SeqList* C);
int main()
{
DataType a[] = { 8,17,17,25,29 };
DataType b[] = { 3,9,21,21,26,57 };
DataType e;
SeqList A, B, C;
InitList(&A);
InitList(&B);
InitList(&C);
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
InsertElem(&A, i, a[i]);
}
for (int i = 0; i < sizeof(b) / sizeof(b[0]); i++)
{
InsertElem(&B, i, b[i]);
}
printf("顺序表A中的元素:\n");
for (int i = 0; i < A.length; i++)
{
GetElem(A, i, &e);
printf("%4d", e);
}
printf("\n");
printf("顺序表B中的元素:\n");
for (int i = 0; i < B.length; i++)
{
GetElem(B, i, &e);
printf("%4d", e);
}
printf("\n");
printf("将顺序表A和B合并得到C:\n");
MergeList(A, B, &C);
for (int i = 0; i < C.length; i++)
{
GetElem(C, i, &e);
printf("%4d", e);
}
return 0;
}
void MergeList(SeqList A, SeqList B, SeqList* C)
{
int i, j, k;
i = j = k = 0;
DataType e1, e2;
while (i < A.length-1 && j < B.length-1)
{
GetElem(A, i, &e1);
GetElem(B, j, &e2);
if (e1 <= e2)
{
InsertElem(C, k, e1);
i++;
k++;
}
else
{
InsertElem(C, k, e2);
j++;
k++;
}
}
while (i <= A.length - 1)
{
GetElem(A, i, &e1);
InsertElem(C, k, e1);
i++;
k++;
}
while (j <= B.length - 1)
{
GetElem(B, j, &e2);
InsertElem(C, k, e2);
j++;
k++;
}
C->length = A.length + B.length;
}
SeqList.h文件
cpp
#pragma once
#include<stdio.h>
#include"SeqList.h"
typedef int DataType;
constexpr auto MaxSize = 100;
typedef struct
{
DataType data[MaxSize];
int length;
}SeqList;
void InitList(SeqList* L);
int ListEmpty(SeqList L);
int GetElem(SeqList L, int i, DataType* e);
int LocateElem(SeqList L, DataType e);
int InsertElem(SeqList* L, int i, DataType e);
int DeleteElem(SeqList* L, int i, DataType* e);
int ListLength(SeqList L);
void ClearList(SeqList* L);
SeqList.cpp文件
cpp
#include "SeqList.h"
#define _CRT_SECURE_NO_WARNINGS 1
void InitList(SeqList* L)
{
L->length = 0;
}
int ListEmpty(SeqList L)
{
if (L.length == 0)
{
return 1;
}
else
return 0;
}
int GetElem(SeqList L, int i, DataType* e)
{
if (i<0 || i>L.length-1)
{
return 0;
}
*e = L.data[i];
return 1;
}
int LocateElem(SeqList L, DataType e)
{
int i;
for (i = 0; i < L.length; i++)
{
if (L.data[i] == e)
return i;
}
return -1;
}
int InsertElem(SeqList* L, int i, DataType e)
{
if (i<0 || i>L->length+1)
{
printf("插入位置i不合法!\n");
return -1;
}
else if(L->length>=MaxSize)
{
printf("顺序表已满,不能插入元素!\n");
return 0;
}
else
{
int j;
for (j = L->length; j >= i; j--)
{
L->data[j+1] = L->data[j];
}
L->data[i] = e;
(L->length++);
return 1;
}
}
int DeleteElem(SeqList* L, int i, DataType* e)
{
if (i > L->length - 1 || i < 0)
{
printf("删除位置不合适!\n");
return 0;
}
else
{
int j;
*e = L->data[i];
for (j = 0; j < i; j++)
{
L->data[j] = L->data[j + 1];
}
(L->length--);
return 1;
}
}
int ListLength(SeqList L)
{
return L.length;
}
void ClearList(SeqList* L)
{
L->length = 0;
}