严蔚敏--线性表的顺序表示和实现 代码

来源:互联网 发布:北京seo待遇 编辑:程序博客网 时间:2024/04/29 06:31


#include<iostream>#include<stdio.h>#include<stdlib.h>using namespace std;//----------线性表的动态分配顺序存储结构-------------#define LIST_INT_SIZE 100#define LISTINCREATMENT 10#define OVERFLOW -2#define OK 1#define ERROR 0typedef int ElemType;typedef struct {  ElemType *elem;  int length;  int listsize;/*当前分配的存储容量*/}SqList;int InitList(SqList &L){//初始化  L.elem=(ElemType*)malloc(LIST_INT_SIZE*sizeof(ElemType));  if(!L.elem)exit(OVERFLOW);  L.length=0;  L.listsize=LIST_INT_SIZE;  return OK;}int ListInsert(SqList&L,int i,ElemType e){//插入元素  if(i<1||i>L.length+1)return ERROR;  if(L.length>>L.listsize){    ElemType*newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREATMENT)*sizeof(ElemType));    if(!newbase)exit(OVERFLOW);    L.elem=newbase;    L.listsize+=LISTINCREATMENT;  }  ElemType*q=&(L.elem[i-1]);  for(ElemType*p=&(L.elem[L.length-1]);p>=q;--p)*(p+1)=*p;  *q=e;  ++L.length;  return OK;}int ListDelete(SqList&L,int i,ElemType&e){//删除元素  if(i<1||i>L.length)return ERROR;  ElemType*p=&(L.elem[i-1]);  e=*p;  ElemType*q=&(L.elem[L.length-1]);  for(++p;p<=q;++p)*(p-1)=*p;  --L.length;  return OK;}void PrintList(SqList L){//打印  for(int i=0;i<L.length;++i)    cout<<L.elem[i]<<" ";  cout<<endl;  cout<<L.length<<endl;}int main(int argc, char **argv){  //测试  SqList L;InitList(L);  int a[]={1,3,5,7,9,2,4,6,8};  for(int i=0;i<9;++i)ListInsert(L,i+1,a[i]);  PrintList(L);    return 0;}




	
				
		
原创粉丝点击