标签:
线性表分为顺序表和链表。
顺序表的基本操作如下:
#include <stdio.h> #include <stdlib.h> /*---------------------------------------------*/ #define INIT_VOLUME_OF_LIST 100 #define INCRESE_VOLUME 10 /*---------------------------------------------*/ typedef char ElemType; typedef struct { ElemType* elem; int iCurrentVolume; int iCurrentLength; int iIncreseVolume; }SqList; /*---------------------------------------------*/ void ErrorMsg(char *s); void testSq(SqList L); void SqListInit(SqList* L); int SqLocateElem(SqList L,ElemType e); void SqInsertElem(SqList* L,int i,ElemType e); /*---------------------------------------------*/ void ErrorMsg(char *s) { printf("%s",s); } /*---------------------------------------------*/ void testSq(SqList L) { int i=0; printf("%d %d %d %d \n",L.elem,L.iCurrentLength,L.iCurrentVolume,L.iIncreseVolume); if(L.iCurrentLength != 0) while(i<=L.iCurrentLength-1) printf("L.elem[%d] = '%c'\n",i-1,L.elem[i++]); } /*---------------------------------------------*/ void SqListInit(SqList* L) { L->elem = (ElemType* )malloc(sizeof(ElemType)*L->iCurrentVolume); if( !(L->elem) ) { ErrorMsg("Malloc failed!"); exit(1); } L->iCurrentLength = 0; L->iCurrentVolume = INIT_VOLUME_OF_LIST; L->iIncreseVolume = INCRESE_VOLUME; } /*---------------------------------------------*/ void SqInputInitData(SqList* L,int n) { ElemType c='a'; int i = 1; if(n>L->iCurrentVolume) { ErrorMsg("Out of Volume,please expand Volume!"); exit(1); } while(n--) { SqInsertElem(L,i,c); i++; c += 1; } } /*---------------------------------------------*/ int SqLocateElem(SqList L,ElemType e) { int iSequenceNum=0; ElemType* p = NULL; p = L.elem; while(iSequenceNum<=L.iCurrentLength && *p!=e) { iSequenceNum++; p++; } if(iSequenceNum<=L.iCurrentLength) return iSequenceNum; return 0; } /*---------------------------------------------*/ void SqInsertElem(SqList* L,int i,ElemType e) { //insert e before i ElemType* p=NULL; ElemType* q=NULL; if(i<1 || i>L->iCurrentLength+1) { ErrorMsg("i is out of range!"); exit(1); } p = &(L->elem[i-1]); for(q=p;q>&(L->elem[L->iCurrentLength-1]);q--) *(p+1) = *p; *p = e; L->iCurrentLength++; } /*---------------------------------------------*/ int main() { SqList La; SqListInit(&La); SqInputInitData(&La,26); testSq(La); return 0; } /*---------------------------------------------*/
void ErrorMsg(char *s);/*错误输出函数*/
void testSq(SqList L);/*对线性表是否成功初始化做简单测试*/
void SqListInit(SqList* L);/*初始化线性表为空表*/
int SqLocateElem(SqList L,ElemType e);/*定位顺序表元素*/
void SqInsertElem(SqList* L,int i,ElemType e);/*在i之前插入一个元素*/
void SqInputInitData(SqList* L,int n);/*初始化线性表数据*/
标签:
原文地址:http://blog.csdn.net/oimchuan/article/details/44172375