标签:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define INIT_SIZE 100
#define PER_INCREMENT 10
typedef struct SqList{
char *Element;
int Length;
int ListSize;
}SqList;
void InitSqList(SqList *L)
{
L->Element=(char*)malloc(sizeof(SqList)*INIT_SIZE);
if(!L->Element) exit(0);
L->Length=0;
L->ListSize=INIT_SIZE;
}
void createSqList(SqList *L)
{
char c;
while((c=getchar())!=‘\n‘)
{
if(c!=‘ ‘)
{
*(L->Element+L->Length)=c;
L->Length++;
}
}
}
char getElement(SqList L,int pos)
{
return *(L.Element+pos-1);
}
void InsertElement(SqList *L,int pos,char e)
{
if(pos<1||pos>L->Length+1) exit(0);
if(L->Length>=L->ListSize)
{
L->Element=(char*)realloc(L->Element,sizeof(char)*(PER_INCREMENT+L->ListSize));
L->ListSize=L->ListSize+PER_INCREMENT;
}
char *p=L->Element+pos-1;
char *q;
for(q=L->Element+L->Length-1;q>=p;--q)
*(q+1)=*q;
*p=e;
L->Length++;
}
char DeleteElement(SqList *L,int pos)
{
if(pos<1||pos>L->Length) exit(0);
char *p=L->Element+pos;
char *q;
for(q=p;q<L->Element+L->Length;++q)
*(q-1)=*q;
L->Length--;
return *p;
}
void destroy(SqList *L)
{
free(L->Element);
}
void printSqList(SqList L)
{
int i=0;
for(;i<L.Length;++i) printf("%c ",*(L.Element+i));
}
void reversePrint(SqList L)
{
int i=L.Length-1;
for(;i>-1;--i) printf("%c ",*(L.Element+i));
}
int main()
{
SqList L;
// 初始化和创建函数的测试
InitSqList(&L);
createSqList(&L);
printSqList(L);
printf("\n");
reversePrint(L);
printf("\n");
// 测试增加函数
int index=0;
int num=0;
srand((unsigned)time(NULL));
for(;index<100;index++)
{
num=rand()%(index+1)+1;
InsertElement(&L,num,num+‘0‘);
}
printSqList(L);
printf("\n");
reversePrint(L);
printf("\n%d",L.Length);
printf("\n");
// 测试删除函数
index=0;
num=0;
srand((unsigned)time(NULL));
for(;index<50;index++)
{
num=rand()%(L.Length);
DeleteElement(&L,num);
}
printSqList(L);
printf("\n");
reversePrint(L);
printf("\n%d",L.Length);
return 0;
}
标签:
原文地址:http://www.cnblogs.com/XuJianShen/p/4244894.html