6-18 数据结构考题 - 顺序表的插入

以顺序表作存储结构,实现线性表的插入。

顺序表定义如下:

#define MAXSIZE 10
typedef int ElemType;
typedef struct

    ElemType  *elem; 
    int length; 
} SqList;
 

 

下面给出了 线性表插入 函数的大部分内容,但缺少了一部分(以下划线____标识出来的部分)。

请先将以下代码中画横线的部分补充完整,然后将完整的函数ListInsert提交系统,完成题目要求的功能。

函数接口定义:

bool ListInsert(SqList &L,int i,ElemType e)

    int j;
    if(i<____ ||i> ____ )
    { 
        cout<<"Insert position error!" ; 
        return  false; 
    }
    if( ____ )
    { 
        cout<<"OVERFLOW!" ;
        return  false; 
    }
    for( j=____ ;j>=____;j--)
        L.elem[ ____ ]=L.elem[ ____ ];
    L.elem[ ____ ]=e;
    L.length++;
    return true;
}

 

该函数中的参数说明:

  • int i: 要插入的位置,取值范围是1 ~ L.length
  • ElemType e: 要插入的数据元素
  • 注意:顺序表中第一个元素存储在 L.elem[0]

测试主程序样例:

#include <iostream>
using namespace std;

#define MAXSIZE 10
typedef int ElemType;
typedef struct
{ ElemType  *elem; int length; } SqList;

bool CreateList(SqList &L)
{
  L.elem=new ElemType[MAXSIZE];
  if (!L.elem)  return false;
  cin>>L.length;
  for(int i=0;i<L.length;i++)
     cin>>L.elem[i];
}

//你提交的函数将出现在这个位置
//.....

void print(SqList L)
{ int i;
  for(i=0;i<L.length;i++)
     if (i==0)  cout<<'('<<L.elem[i];
     else cout<<','<<L.elem[i];
  cout<<')'<<endl;
}

int main()
{ SqList L; int i; ElemType e;
  CreateList(L);
  cout<<"Before:";    print(L);
  cin>>i>>e;
  if ( ListInsert(L,i,e) )
    { cout<<"After:";   print(L); }
  return 0;
}
 

 

输入样例:

在这里给出一组输入。例如:

5
1 3 5 7 9
3 4

 

输出样例:

在这里给出相应的输出。例如:

Before:(1,3,5,7,9)
After:(1,3,4,5,7,9)

 样例2,3 省略

bool ListInsert(SqList &L,int i,ElemType e)
{ 
    int j;
    if(i<1 ||i>L.length+1)
    { 
        cout<<"Insert position error!" ; 
        return  false; 
    }
    if( L.length==10 )
    { 
        cout<<"OVERFLOW!" ;
        return  false; 
    }
    for( j=L.length-1 ;j>=i-1;j--)
        L.elem[ j+1 ]=L.elem[ j ];
    L.elem[ i-1 ]=e;
    L.length++;
    return true;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

THK-J

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值