赞
踩
- #include<stdio.h>
- #include<stdlib.h>
-
- #define LIST_INIT_SIZE 10
- #define LISTINCREMENT 5
-
- typedef int ElemType;
-
- struct SqList{
- ElemType *elem;
- int length;
- int listsize;
- };
-
- //初始化线性表
- void InitList_Sq(SqList &L){
- L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
- if(!L.elem){
- printf("ERROR in InitList_Sq\n");
- return;
- }
- L.length = 0;
- L.listsize = LIST_INIT_SIZE;
- }
-
- //销毁线性表
- void DestoryList(SqList &L){
- free(L.elem);
- L.length = 0;
- }
-
- //清空线性表
- void ClearList(SqList &L){
- L.length = 0;
- }
-
- //判断线性表是否为空
- int ListEmpty(SqList L){
- return (L.length==0) ? 1 : 0
- }
-
- //返回线性表的长度
- int ListLength(SqList L){
- return L.length;
- }
-
- //获取线性表中第i个元素
- void GetElem(SqList L, int i, ElemType &e){
- if(i<1||i>L.length){
- printf("OVERFLOW in GetElem\n");
- return;
- }
- e = L.elem[i-1];
- }
-
- //向线性表插入元素
- void InsertList_Sq(SqList &L, int i, ElemType e){
- if(i<1||i>L.length+1){ //这里应该是i>L.length+1,在编写过程中在这里踩过坑
- printf("OVERFLOW in InsertList_Sq\n");
- return;
- }
- if(L.length>=L.listsize){
- ElemType *temp;
- temp = (ElemType *)realloc(L.elem, (L.listsize+LISTINCREMENT)*sizeof(ElemType));//这个部分也应该留意L.listsize+LISTINCREMENT
- if(!temp){
- printf("ERROR in InsertList_Sq\n");
- return ;
- }
- L.elem = temp;
- L.listsize += LISTINCREMENT;
- }
-
- ElemType *ptr, *ptr_last;
- ptr = &(L.elem[i-1]);
- ptr_last = &(L.elem[L.length-1]);//这里和下面的DeleteList_Sq的部分分别为两种取地址的方式,可以灵活使用
- for(ptr_last; ptr_last>=ptr; --ptr_last) *(ptr_last+1) = *(ptr_last);
- *ptr = e;
- ++L.length;
- }
-
- void DeleteList_Sq(SqList &L, int i, ElemType &e){
- if(i<1||i>L.length){
- printf("OVERFLOW in DeleteList_Sq\n");
- return;
- }
-
- ElemType *ptr, *ptr_last;
- e = L.elem[i-1];
- ptr = &(L.elem[i-1]);
- ptr_last = L.elem+L.length-1;
- for(ptr; ptr<ptr_last; ptr++) *ptr = *(ptr+1);
- L.length--;
- }
-
- int main(){
- SqList list;
- int e;
- InitList_Sq(list);
-
- for(int i=1; i<=9; i++){
- InsertList_Sq(list, i, i);
- }
- InsertList_Sq(list, 26, 0);
- InsertList_Sq(list, 5, -1);
- for(int i=0; i<list.length; i++){
- printf("%d ", list.elem[i]);
- }
- printf("\n");
- DeleteList_Sq(list, 13, e);
- printf("%d\n", e);
- for(int i=0; i<list.length; i++){
- printf("%d ", list.elem[i]);
- }
-
-
-
- return 0;
- }
参考:严蔚敏《数据结构C语言版》
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。