【数据结构/C++】线性表_顺序表的基本操作

cpp 复制代码
#include <iostream>
using namespace std;
#define MaxSize 10
// 1. 顺序表
// 静态分配
// 创建匿名结构体
typedef struct
{
  int data[MaxSize];
  int length; // 当前长度
} SqList;
// 静态分配初始化顺序表
// 凡是需要改动原链表都需要引用或者指针传递
void InitList(SqList &L)
{
  for (int i = 0; i < MaxSize; i++)
  {
    L.data[i] = 0;
  }
  L.length = 0;
}
// 插入元素 到第 i 个位置
bool ListInsert(SqList &L, int i, int e)
{
  // 保证i的合法
  if (i < 1 || i > L.length + 1)
  {
    return false;
  }
  // 保证 length 的合法
  if (L.length >= MaxSize)
  {
    return false;
  }
  // 原本 i 位置及以后都向后移动一位
  for (int j = i; j <= L.length; j++)
  {
    L.data[j] = L.data[j - 1];
  }
  // 将 e 插入
  L.data[i - 1] = e;
  // 移动之后再将长度进行增加
  L.length++;
  return true;
}
// 删除第 i 个位置的元素
bool ListDelete(SqList &L, int i, int &e)
{
  // 保证 i 的合法
  if (i < 1 || i > L.length)
  {
    return false;
  }
  // 将被删除的元素赋值给 e,便于输出
  e = L.data[i - 1];
  // 将第 i 位置的元素(索引为 i - 1)及以后的元素向前移动一位
  // 首次移动的索引是 i,最后一次移动的索引是 L.length - 1
  for (int j = i; j < L.length; j++)
  {
    L.data[j - 1] = L.data[j];
  }
  L.length--;
  return true;
}
// 遍历顺序表
void ListTraverse(SqList L)
{
  for (int i = 0; i < L.length; i++)
  {
    cout << L.data[i] << " ";
  }
  cout << endl;
}
int main()
{
  int e;
  SqList L;
  InitList(L);
  ListInsert(L, 1, 1);
  ListInsert(L, 2, 2);
  ListInsert(L, 3, 3);
  ListDelete(L, 2, e);
  cout << "删除的元素是" << e << endl;
  ListTraverse(L);
  return 0;
}
相关推荐
肆忆_19 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20215 天前
信号量和信号
linux·c++