包师.萌新 2022-04-01 08:01 采纳率: 71.4%
浏览 51
已结题

顺序表的有序插入操作

6-40 顺序表的有序插入操作 (10 分)
本题要求实现一个函数,要求将指定元素插入到有序表的合适位置,使得插入后仍然保持有序,若插入失败返回0;插入成功则返回1,并且顺序表的长度加1.

函数接口定义:

int SqInsert(SqList &L,ElemType e);

其中SqList结构定义如下:

typedef struct{
    ElemType *elem;
    int length;
 }SqList;

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
typedef int ElemType;
typedef struct{
    ElemType *elem;
    int length;
}SqList;
void InitList(SqList &L);/*函数的实现此处不再显示*/
int SqInsert(SqList &L,ElemType e);
int main()
{
    SqList L;
    InitList(L);
    ElemType e;
    scanf("%d",&e);
    int result=SqInsert(L,e);
    if(result==0){
        printf("Insertion Error.The storage space is full!");    
    }else if(result==1){
        printf("Insertion Success.The elements of the SequenceList L are:");    
        for(int j=0;j<L.length;j++){
            printf(" %d",L.elem[j]);
        }
    }
    return 0;
}
   
/* 请在这里填写答案 */


输入格式:
输入数据有1行,首先给出以-1结束的非递减顺序表元素值(不超过100个,-1不属于顺序表元素,),然后是被插入元素值。所有数据之间用空格分隔。

输入样例:
4 8 20 -1 10
输出样例:
Insertion Success.The elements of the SequenceList L are: 4 8 10 20

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2022-04-01 09:54
    关注

    供参考:

    #include <stdio.h>
    #include <stdlib.h>
    #define MAXSIZE 5
    typedef int ElemType;
    typedef struct {
        ElemType* elem;
        int length;
    }SqList;
    void InitList(SqList& L);/*函数的实现此处不再显示*/
    int  SqInsert(SqList& L, ElemType e);
    int main()
    {
        SqList L;
        InitList(L);
        ElemType e;
        scanf("%d", &e);
        int result = SqInsert(L, e);
        if (result == 0) {
            printf("Insertion Error.The storage space is full!");
        }
        else if (result == 1) {
            printf("Insertion Success.The elements of the SequenceList L are:");
            for (int j = 0; j < L.length; j++) {
                printf(" %d", L.elem[j]);
            }
        }
        return 0;
    }
    /* 请在这里填写答案 */
    int SqInsert(SqList& L, ElemType e)
    {
        int i;
        if (L.length > MAXSIZE - 1) return 0;
        if (L.elem[L.length - 1] < e)
            L.elem[L.length] = e;
        else{
            for (i = L.length; L.elem[i - 1] > e && i > 0; i--)
                L.elem[i] = L.elem[i - 1];
            L.elem[i] = e;
        }
        L.length++;
        return 1;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月28日
  • 已采纳回答 9月20日
  • 创建了问题 4月1日

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂