C language_Algorithm 1: Given the sequence table L, the elements in the table are integers and are in increasing order. The existing element with a value of e must be inserted into the L table, so that the L table is still in order after insertion.

#include<stdio.h>
#include<stdlib.h>
#define list_size 100
#define listincreasement 100
typedef int element;  // 自定义int类型element 
typedef struct   //顺序表中的一个结点 
{
    element* elem;
    int length;
    int listsize;
}Sqlist;
bool initializer_list(Sqlist& L);//建表初始化 
bool creatnewlist(Sqlist& L, int n);   // 建立顺序表 
void insert_N(Sqlist& L,int N);   //输出顺序表 
int main()
{
    Sqlist L;
    int n,N;
    printf("请输入要建立的顺序表元素个数:\n");
    scanf_s("%d", &n);
    initializer_list(L);
    creatnewlist(L, n);
    printf("请输入要插入的数字:\n");
    scanf_s("%d", &N);
    insert_N(L,N);
    return 0;
}
bool initializer_list(Sqlist& L)  //建表初始化 
{
    L.elem = (int*)malloc(sizeof(int));
    if (!L.elem)
    {
        return 0;
    }
        L.length = 0;
        L.listsize = list_size;
        return 0;
}
bool creatnewlist(Sqlist& L, int n)  // 建立顺序表 
{
    int i;
    L.elem = (int*)malloc(sizeof(int) * list_size);
    if (!L.elem)
    {
        return 0;
    }
    else
    {
        printf("请按照递增的顺序输入数据:\n");
        for (i = 0; i < n; i++)
        {
            scanf_s("%d", &L.elem[i]);
            L.length++;
        }
    }
    return 0;
}
void insert_N(Sqlist& L,int N)  //插入N并输出顺序表 
{
    int i,j;
    for (i = 0; i < L.length; i++)
    {
        if (N <= L.elem[i])
        {
            for (j = L.length; j > i; j--)
            {
                L.elem[j] = L.elem[j - 1];
            }
            L.elem[i] = N;
            break;
        }
    }
    for (i = 0; i < L.length+1; i++)
    {
        printf("%d ", L.elem[i]);
    }
}

Guess you like

Origin blog.csdn.net/qq_51224492/article/details/110372110