voidListInsert(SqList &L, int i, ElemType e) //在顺序表中第i个位置插入元素函数e
void ListDelete(SqList &L, int i, ElemType &e)//删除顺序表L的第i个数据元素,并用e返回其值。
void PrintList(SqList L) // 输出顺序表函数
int Locate(SqList L, ElemType e) //若顺序表L中存在数据元素e,则返回e在顺序表L中第一次出现的位序;否则返回0.
int ListLength(SqList L) //求顺序表L的表长
// 1.编程实现顺序表的基本操作#include<stdio.h>#include<stdlib.h>#include<conio.h>#define LIST_INIT_SIZE 10 // 存储空间的初始分配量#define LISTINCREMENT 10 // 分配增量typedef int ElemType ; // 顺序表中存放的是整数typedef struct {ElemType * elem ; // 存储空间基址int length ; // 当前长度int listsize ; // 当前分配的存储容量} SqList ;
void InitList ( SqList & L ){// 建立一个空的顺序表LL . elem = ( ElemType * ) malloc ( LIST_INIT_SIZE * sizeof ( ElemType ));if ( L . elem ){L . length = 0 ;L . listsize = LIST_INIT_SIZE ;}}
void CreateSqList ( SqList & L , int m ){// 初始条件:顺序表L已存在// 操作结果:将m个元素依次加入顺序表Lint i ;for ( i = 0 ; i < m ; i ++ ){scanf ( "%d" , & L . elem [ i ]);L . length ++ ;if ( L . length >= L . listsize ){L . elem = ( ElemType * ) realloc ( L . elem ,( L . listsize + LISTINCREMENT ) * sizeof ( ElemType ));L . listsize += LISTINCREMENT ;}}}
void ListInsert ( SqList & L , int i , ElemType e ){// 初始条件:顺序表L已存在,1<=i<=ListLength(L)+1// 操作结果:在顺序表L中第i个位置之前插入新的数据元素e,表长加1ElemType * p , * q ;if ( i < 1 || i > L . length + 1 )exit ( - 2 );if ( L . length >= L . listsize ){L . elem = ( ElemType * ) realloc ( L . elem ,( L . listsize + LISTINCREMENT ) * sizeof ( ElemType ));L . listsize += LISTINCREMENT ;}q = & ( L . elem [ i - 1 ]);for ( p = & ( L . elem [ L . length - 1 ]); p >= q ; -- p )* ( p + 1 ) = * p ;* q = e ;++ L . length ;}
void ListDelete ( SqList & L , int i , ElemType & e ){// 初始条件:顺序表L已存在,1<=i<=ListLength(L)// 操作结果:删除顺序表L的第i个数据元素,并用e返回其值ElemType * p ;if ( i < 1 || i > L . length )exit ( - 2 );e = L . elem [ i - 1 ];for ( p = & L . elem [ i - 1 ]; p <= & L . elem [ L . length - 1 ]; p ++ )* ( p - 1 ) = * p ;-- L . length ;}
void PrintList ( SqList L ){// 初始条件:顺序表L已存在// 操作结果:打印顺序表int i ;for ( i = 0 ; i < L . length ; i ++ )printf ( "%d " , L . elem [ i ]);}
int Locate ( SqList L , ElemType e ){// 初始条件:顺序表L已存在// 操作结果:若顺序表L中存在数据元素e,则返回e在顺序表L中第一次出现的位序;否则返回0int i , result = 0 ;for ( i = 0 ; i < L . length ; i ++ ){if ( L . elem [ i ] == e ){result = i + 1 ;break ;}}return result ;}
int ListLength ( SqList L ){// 初始条件:顺序表L已存在// 操作结果:返回顺序表L的表长return L . length ;}
int main (){SqList L ;int n , i ;ElemType e ;InitList ( L );printf ( "请输入表长:" );scanf ( "%d" , & n );printf ( "请输入元素(空格分隔):" );CreateSqList ( L , n );printf ( "顺序表为:" );PrintList ( L );printf ( " \n " );printf ( "输入插入位置和元素(空格分隔):" );scanf ( "%d %d" , & i , & e );ListInsert ( L , i , e );printf ( "顺序表为:" );PrintList ( L );printf ( " \n " );printf ( "输入删除位置:" );scanf ( "%d" , & i );ListDelete ( L , i , e );printf ( "删除元素为:%d \n " , e );printf ( "输入待查找元素:" );scanf ( "%d" , & e );printf ( "查找结果:%d \n " , Locate ( L , e ));printf ( "顺序表表长:%d \n " , ListLength ( L ));printf ( "按任意键结束... \n " );char ch = getch ();return 0 ;}