顺序表应用3:元素位置互换之移位算法

本文介绍了一个使用C++实现的顺序表的基本操作案例,包括初始化、插入元素及特定位置元素交换等实用功能。通过对代码的解析,读者可以了解如何在C++中管理动态数组并实现基本的数据结构操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <bits/stdc++.h>
using namespace std;

#define  LISTINCREASMENT 100
#define  LISTSIZE 10010
#define  OVERLFLOW -1
#define  OK 1
typedef int ElemType;

typedef struct
{
    ElemType *elem;
    int length;
    int listsize;
} Sqlist;

int SqInitial(Sqlist &L)
{
    L.elem = (ElemType *)malloc(LISTSIZE*sizeof(ElemType));
    if(!L.elem) return OVERFLOW;
    L.length=0;
    L.listsize=LISTSIZE;
    return OK;
}

int ListInsert(Sqlist &L,int i, ElemType e)
{
    if(L.length >= L.listsize)
    {
        ElemType *newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREASMENT)*sizeof(ElemType));
        L.elem = newbase;
        L.listsize+=LISTINCREASMENT;
    }
    ElemType *q= &(L.elem[i]);
    *q = e;
    ++L.length;
    return OK;
}

void exchang(Sqlist &L, int m)
{
  for(int i = 0,j = m; j < L.length; i++,j++)
  {
      int tmp = L.elem[j];
      for(int k = j; k > i; k--)
       L.elem[k] = L.elem[k-1];
       L.elem[i] = tmp;
  }
}

void print(Sqlist &L)
{
   for(int i = 0; i < L.length; i++)
   {
    i == L.length-1 ? cout << L.elem[i] << endl : cout << L.elem[i] << ' ';
   }
}

int main()
{
    int k;
    int n,m;
    cin >> k;
    while(k --)
    {
     Sqlist L;
     SqInitial(L);
     scanf("%d %d", &n, &m);
     for(int i = 0; i < n; i++)
     {
       int e;
       scanf("%d",&e);
       ListInsert(L,i,e);
     }
     exchang(L,m);
     print(L);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值