数据结构——线性表的建立和有序输出

建立空的线性表;
输入表中的元素;
在输入的过程中将输入的元素依次插入建立好的线性表中;
在插入的过程中排序;
输出已经排序好了的有序线性表;

#include<iostream>
#include<stdlib.h>
# define LIST_INIT_SIZE 100
# define LISTINCREMENT 10
# define ElemType int
# define OVERFLOW -1
# define ERROR -1
using namespace std;
typedef struct {
    ElemType *elem;
    int length;
    int listsize;
}SqList;
void InitList_Sq(SqList &L)
{
    L.elem = (ElemType * )malloc(LIST_INIT_SIZE*sizeof(ElemType));
    if(! L.elem)
        exit(OVERFLOW);
    L.length = 0;
    L.listsize = LIST_INIT_SIZE;
}
int ListInsert_Sq(SqList &L, int i, ElemType e)
{

    if(i > L.length)
    {
        cout << "ERROR";
        return ERROR;
    }
    if(L.length >= L.listsize)
    {
        ElemType *newbase;
        newbase = (ElemType *)realloc(L.elem,(L.listsize + LISTINCREMENT) * sizeof(ElemType));
        if(!newbase)
        exit(OVERFLOW);
        L.elem = newbase;
        L.listsize += LISTINCREMENT;
    }

    if(L.length == 0)
    {
        L.elem[0] = e;
        L.length++;
        return 1;
    }
    else
    {
        ElemType *p, *q;
        int wh;
        for(wh = 0; wh < L.length; wh++)
        {
            if( L.elem[wh] > e)
                break;
        }
        q = &L.elem[wh];
        for( p = &(L.elem[L.length-1]); p >= q; p--)
            *(p+1) = *p;
         *q = e;
        L.length++;
    }
}
int main ()
{
    SqList L;
    InitList_Sq(L);
    int e;
    int n;
    cout << "Please input n:" << endl;
    cin >> n;
    cout << "Please input elem:" << endl;
    for(int i = 0; i < n; i++)
    {
        cin >> e;
        ListInsert_Sq( L, i, e);
    }
    cout << "Output the SqList:" << endl;
    for(int i = 0; i < L.length; i++)
        cout << L.elem[i] << " ";
    cout << endl;
    free(L.elem);
    L.elem = NULL;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值