// 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;
}
数据结构--线性表
最新推荐文章于 2022-09-07 23:56:41 发布