数据结构 顺序表中插入和删除元素的算法、顺序栈中入栈和出栈的算法
发布网友
发布时间:2022-05-22 01:10
我来回答
共1个回答
热心网友
时间:2023-11-23 21:37
//顺序表的插入
void Insert(int i, int item)
{
if (length >= MaxSize)
{
cerr << "上溢";
exit(1);
}
if (i<1 || i>length + 1)
{
cerr << "插入位置非法";
exit(1);
}
for (int j = length; j >= i - 1; j--)
data[j + 1] = data[j];
data[i - 1] = item;
length++;
}
//顺序表的删除
int Delete(int i)
{
if (length == 0)
{
cerr << "下溢";
exit(1);
}
if (i<1 || i>length)
{
cerr << "删除位置非法";
exit(1);
}
int x = data[i - 1];
for (int j = i; j < length; j++)
data[j - 1] = data[j];
length--;
return x;
}
//入栈操作
void Push(T x)
{
if (top == MaxSize - 1)
{
cerr << "上溢";
exit(1);
}
top++;
data[top] = x;
}
//出栈操作
int Pop()
{
if (top == -1)
{
cerr << "下溢";
exit(1);
}
int x = data[top--];
return x;
}