⼤⼀新⼿学习线性表-顺序表的合并(C语⾔)#ifndef _SQLIST_H_
#define _SQLIST_H_
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//线性顺序表
#define MAXSIZE 10
#define OVERFLOW -1
#define OK 1
#define ERROR -2
//类型重定义
typedef int ElemType;
typedef int Status;
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
Status InitList(SqList *L){
//构造⼀个空的线性表
L->elem = (ElemType*)malloc(MAXSIZE * sizeof(ElemType));
if (!L->elem)
exit(OVERFLOW);
memset(L->elem, 0, MAXSIZE*sizeof(ElemType));
L->length = 0;
L->listsize = MAXSIZE;
return OK;
}
Status GetElem(SqList *L, int i){
//顺序表的取值
Status e = 0;
if (i<0 || i>L->length)
return ERROR;
e = L->elem[i - 1];
return e;
}
Status ListLength(SqList *L){
//顺序表的长度
return L->length;
}
int LocateElem(SqList L, ElemType e){
//在顺序表L中查值为e的数据元素,返回其序号
int i;
for (i = 0; i < L.length; i++) {
if (e == L.elem[i]) {
return i+2; //存储存在问题
}
}
return ERROR;
}
Status ListInsert(SqList *L, int i, ElemType e){
//在顺序表L中第i个位置之前插⼊新的元素e,i值的合法范围是1<=i<=L->length+1 ElemType *p;
ElemType *q = &L->elem[i - 1];
if (i < 0 || i > L->length + 1) {
return ERROR;
}
for (p = &L->elem[L->length]; p >= q; p--) {
*(p + 1) = *p;
}
*q = e;c语言listinsert函数
L->length++;
return OK;
}
Status ListDelete(SqList *L, int i){
//在顺序表L中删除第i个元素,i的合法范围是1<=i<=L->length
if ((i<1) || (i>L->length)) return ERROR;
for (int j = 0; j <= L->length; j++){
L->elem[j - 1] = L->elem[j];
}
--L->length;
return OK;
}
Status ClearList(SqList *L){
//清空线性表
L->length = 0;
return ERROR;
}
Status ListDestroy(SqList *L){
//销毁线性表
free(L);
return ERROR;
}
#endif
#include"SqList.h"
#include<stdio.h>
#include<stdlib.h>
void MergeList(SqList *LA, SqList *LB){
//将所有在线性表LB中但不在LA中的元素插⼊到LA中
int m = ListLength(LA);
int n = ListLength(LB);
for (int i = 0; i < n; i++){
for (int i = 0; i < n; i++){
int e = GetElem(LB, i);
if (LocateElem(*LA, e))
ListInsert(LA, m++, e);
}
}
int main(){
SqList LA;
SqList LB;
InitList(&LA);
InitList(&LB);
int n = 0;
int val = 0;
printf("输⼊你想在LA中插⼊元素的个数:"); scanf_s("%d", &n);
for (int i = 0; i < n; i++){
printf("输⼊LA的第%d个元素:", i + 1); scanf_s("%d", &val);
ListInsert(&LA, i, val);
}
printf("输⼊你想在LB中插⼊元素的个数:"); scanf_s("%d", &n);
for (int i = 0; i < n; i++){
printf("输⼊LB的第%d个元素:", i + 1); scanf_s("%d", &val);
ListInsert(&LB, i, val);
}
printf("LA中的元素是:");
n = ListLength(&LA);
for (int i = 0; i < n; i++){
int e = GetElem(&LA, i);
printf("%d ", e);
}
printf("\n");
printf("LB中的元素是:");
n = ListLength(&LB);
for (int i = 0; i < n; i++){
int e = GetElem(&LB, i);
printf("%d ", e);
}
printf("\n");
printf("输⼊你想在LB中查的元素:"); scanf_s("%d", &n);
printf("%d\n", LocateElem(LB, n)); MergeList(&LA, &LB);
printf("合并过后的LA为:");
n = ListLength(&LA);
printf("%d\n", n);
for (int i = 0; i < n; i++){
int e = GetElem(&LA, i);
printf("%d ", e);
}
printf("\n");
// ListDestroy(&LA);
// ListDestroy(&LB);
return 0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论