顺序表插入

题目描述

【问题描述】查找顺序表第i个位置(逻辑位序)插入新元素e。若插入位置不合法,则返回false,输出“The insertion position does not exist”和顺序表的表长。成功则输出插入后的新表。假设顺序表的元素为整型数据。

【输入形式】第1行顺序表的长度;第2行顺序表各数据元素;第3行为插入位置和插入元素。

【输出形式】若顺序表插入成功,则先输出插入后的顺序表,插入失败则输出“The insertion position does not exist”和顺序表的表长。

【样例输入】 

       10

       8 19 96 38 83 47 67 72 93 82

       5 20

【样例输出】

        8 19 96 38 20 83 47 67 72 93 82

【样例输入】

        8

       19 30 90 92 0 95 20 51

       15 30

【样例输出】

       The insertion position does not exist

       8


解题思路

        根据题意写出实现顺序表的框架代码,判断删除索引是否合理并进行插入返回0/1代表插入是否合法,将顺序表插入索引处后移并插入值


源代码

#include <iostream>
#include <stdlib.h>
using namespace std;
#define MaxSize 100
typedef int ElemType;

typedef struct {
	ElemType data[MaxSize];
	int length;
} SqList;

void InitList(SqList& L) {  //初始化顺序表
	//L = (SqList*)malloc(sizeof(SqList));
	L.length = 0;
}
int InsElem(SqList& L, int i, int e) {   //按索引插入
	if (i<1 || i>L.length)
		return 0;
	int j;
	for (j = L.length; j > i - 1; j--) 
		L.data[j] = L.data[j - 1];
	L.data[i - 1] = e;
	L.length++;
	return 1;

}
void PrintElem(SqList L) {  //输出顺序表
	int i;
	for (i = 0; i < L.length; i++)
		cout << L.data[i] << " ";
	cout << endl;
}
int main() {
	int n, i, e;
	SqList L;
	InitList(L);
	cin >> n;
	for (i = 0; i < n; i++) {
		cin >> L.data[i];
		L.length++;
	}
	cin >> i;
	cin >> e;
	if (InsElem(L, i, e)) {
		PrintElem(L);
	}
	else {
		cout << "The insertion position does not exist" << endl;
		cout << L.length << endl;
	}
	system("pause");
	return 0;
}

总结

        顺序表的简单应用~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想我记得写信

您的鼓励是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值