顺序表的插入

定义一个结构体

# include<iostream>
# include<cstdio>
# include<cstdlib>
using namespace std;
typedef struct
{
    int *elem;
    int length;
    int maxsize;
} ListNode;
View Code

初始化ListNode

void InitList(ListNode &L)
{
    L.elem = (int *)malloc(sizeof(int));
    if(L.elem == NULL)
        exit(-1);
    L.length = 0;
    L.maxsize = 100;
}
View Code

ListNode的插入

void Insert_List(ListNode &L,int i,int *e)
{
    int *current,*p,*q;
    if(i <= 1||i >= L.length + 1)
    {
        exit(-1);
    }
    if(L.length > L.maxsize)
    {
        current = (int *)malloc(sizeof(int));
        L.elem = current;
        L.maxsize = L.maxsize+100;
    }
    q=&(L.elem[i-1]);
    for(p=&(L.elem[L.length-1]); p>=q; p--)
    {
        *(p+1)=*p;
    }
    *q=*e;
    L.length++;
}
View Code

新ListNode的输出

void Output_List(ListNode &L)
{
    for(int i = 0; i < L.length; i++)
        cout<<L.elem[i]<<endl;
}
View Code

main的测试

int main()
{
    ListNode L1;
    InitList(L1);
    int LI1=8;
    int *LI2;
    LI2=&LI1;
    L1.length = 10;
    for(int j = 0; j < L1.length; j++)
    {
        L1.elem[j] = j;
    }
    Insert_List(L1,5,LI2);
    Output_List(L1);
    return 0;

}
View Code
原文地址:https://www.cnblogs.com/sxmcACM/p/3350181.html