从新在学习一遍数据结构,每天尽量都写点!
/* * Fuction: the list struct! * By: xiaolong * Date: 2012年 03月 13日 星期二 16:50:12 CST * 功能:线性表的顺序存储实现 * 主要功能: * * */ #include<stdio.h> #include<stdlib.h> #define MAX_SIZE 20 #define ADD_SIZE 10 //这里定义了一个结构,用来存放顺序表:首位置,空间大小,数据长度 typedef struct{ int *entry; int size; int length; }SqList; // 初始化函数 int InitList(SqList *l) { l->entry = (int *)malloc(MAX_SIZE*sizeof(int)); if(l->entry==NULL) { printf("Init failure!\n"); return -1; } l->size = MAX_SIZE; l->length = 0; return 0; } //删除顺序表函数,其实就是释放之前初始化中malloc的空间地址 //这里犯了一个错误,就是将l也进行释放了,因为我之前声明结构的时候,不是声明的地址 void DeleteList(SqList *l) { free(l->entry); } //插入函数:在顺序表l中,按照指定的位置n,插入指定的元素e int InsertElem(SqList *l,int e,int n) { int i; if(n<0 || n > l->length) //判断参数时候符合要求 { printf("Insert number is wrong!\n"); return -1; } if(l->size == l->length) { int *new_entry=(int*)realloc(l->entry,(l->size+ADD_SIZE)*sizeof(int)); if(new_entry==NULL) { printf("Extenting the space is failure !\n"); return -1; } l->entry =new_entry; l->size += ADD_SIZE; } //进行插入,将插入位置以后的元素全部后移一位 for(i = l->length-1;i>=n;--i) { l->entry[i+1]=l->entry[i]; } //将指定元素插入 l->entry[n]=e; l->length ++; return 0; } //打印所有的元素,如果有元素的话! int Print(SqList *l) { int i; if(l->length ==0) { printf("The list has no data!\n"); return -1; } for(i=0;i<l->length;++i) { printf("%d ",l->entry[i]); if((i+1)%5==0) printf("\n"); } printf("\n"); return 0; } //顺序链表l中,指定的下标n,删除元素,并将删除的元素赋给e int RmElem(SqList *l,int *e,int n) { int i; if(n <0 || n >l->length) { printf("The remove number N is wrong!\n"); return -1; } *e=l->entry[n]; for(i=n;i<l->length;i++) { l->entry[i]=l->entry[i+1]; } l->length--; return 0; } int main(int argc,char ** argv) { SqList l; int in; //输入的元素 int n=0; int elem; //删除的元素 if(InitList(&l)==-1) { return -1; } //插入元素,循环插入元素 while(1) { printf("Please input the data(int):"); scanf("%d",&in); if(in ==111) break; //如果是111,就不再询问插入数值,跳出循环 InsertElem(&l,in,n++); } //打印元素 Print(&l); //删除指定位置的元素 while(1) { printf("Please input the index you want to remove:"); scanf("%d",&in); //如果是111,就不再询问删除下标,跳出循环 if(in ==111) break; RmElem(&l,&elem,in); } Print(&l); //摧毁线性表 DeleteList(&l); return 0; }
数据结构之线性表--顺序存储
最新推荐文章于 2024-07-23 12:29:02 发布