数据结构--线性表

本文详细介绍了C++中线性表的初始化、插入、删除等操作的实现过程,通过实例展示了具体代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Liner.cpp : Defines the entry point for the console application.
/*-----CODE FOR FUN---------------
-------CREATED BY Dream_Whui--
-------2015-1-20--------------------*/

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;

#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10

#define  ElemType char

#define   TRUE             1
#define   FALSE            0
#define   OK                 1
#define   ERROR            0
#define   OVERFLOW   -2
#define   INFEASIBLE   -1

typedef struct
{
    ElemType *elem;    //表的起始位置
    int length;                 //表的实际长度
    int listsize;                //分配的存储容量
}SqList;

int InitList_Sq(SqList &L)//初始化线性表,实际长度为0,存储容量为100
{
    L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
    if(!L.elem)
        exit( OVERFLOW);
    L.length = 0;
    L.listsize = LIST_INIT_SIZE;
    return OK;
}

int ListInsert_Sq(SqList &L,int i,ElemType e)//线性表的插入操作,在第i个位置前面插入元素e
{
    ElemType * newbase;
    if(i<1 || i>L.length+1)//判读插入的位置是否合法
        return ERROR;
    if(L.length >= L.listsize)//实际长度大于等于存储容量后,应扩大存储空间
    {
        newbase = (ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
        if(!newbase)
            exit(OVERFLOW);
        L.elem = newbase;
        L.listsize +=LISTINCREMENT;
    }
    ElemType *q = &L.elem[i-1];//取插入位置元素的地址
    ElemType *p = &L.elem[L.length-1];//取表的最后一个元素的地址
    for( ;p>=q;p--)//第i位置到最后一个位置的元素都向后移动一个位置
    {
        *(p+1) = *p;
    }
    *q = e;
    ++L.length;
    return OK;
}

int ListDelete_Sq(SqList &L,int i,ElemType &e)//线性表的删除操作,删除第i个位置上的元素
{
    if(i<1 || i>L.length)//判断位置i是否合法
        return ERROR;
    ElemType* q = &L.elem[i-1];//取第i个位置的元素地址
    ElemType* p = &L.elem[L.length-1];//取最后一个元素的地址
    e = *q;
    for( ;q<=p;q++)//第i位置到最后一个位置上的元素都向前移动一位
    {
        *q = *(q+1);
    }
    --L.length;
    return OK;
}
int main(int argc, char* argv[])
{
    SqList L;
    InitList_Sq(L);
    L.elem[0]='A';
    L.length++;
    cout<<L.length<<" "<<L.listsize<<endl;
    cout<<L.elem[0]<<endl;
    ListInsert_Sq(L,1,'A');
    ListInsert_Sq(L,1,'B');
    ListInsert_Sq(L,1,'C');
    ListInsert_Sq(L,1,'D');
    ListInsert_Sq(L,1,'E');
    ListInsert_Sq(L,1,'F');
    cout<<L.length<<" "<<L.listsize<<endl;
    for(int i=0;i<L.length;i++)
        cout<<L.elem[i]<<" ";
    cout<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值