标签:tab 线性 span div new realloc length sizeof nbsp
昨天留的作业,数据结构书和c语言书真的不一样,需要自己加加补补,今天写的时候迷迷瞪瞪的,反正在我电脑上能用。
数据结构线性表插入删除的示例:
代码:
#include<iostream> #include<cstdio> using namespace std; #define list_init_size 100 #define listincrement 10 typedef struct { int *elem; int length; int listsize; }sqlist; int display(sqlist l)//显示函数 { for(int k=0;k<l.length;k++) cout<<l.elem[k]<<"\t"; cout<<endl; return 0; } int initlist_sq(sqlist &l) { l.elem=(int *)malloc(list_init_size*sizeof(int)); if(!l.elem) exit(0); l.length=0; l.listsize=list_init_size; return 1; } int listinsert_sq(sqlist &l,int i,int e)//插入 { if(i<1||i>l.length+1) return 0; int *newbase; if(l.length>=l.listsize) { newbase=(int*)realloc(l.elem,(l.listsize+listincrement)*sizeof(int)); if(!newbase) exit(0); l.elem=newbase; l.listsize+=listincrement; } int *q=&(l.elem[i-1]); for(int *p=&(l.elem[l.length-1]);p>=q;p--) *(p+1)=*p; *q=e; l.length++; return 1; } int listdelete_sq(sqlist &l,int i,int &e)//删除 { if(i<1||i>l.length) return 0; int *pp; pp=&(l.elem[i-1]); int *qq=l.elem+l.length-1; for(++pp;pp<=qq;++pp) *(pp-1)=*pp; l.length--; return 1; } int main() { sqlist l; cout<<"Please enter the length of the linear table:"; initlist_sq(l); cin>>l.length; for(int j=0;j<l.length;j++) { cin>>l.elem[j]; } display(l); int place; cout<<"Please enter the number of positions to insert:"; cin>>place; int num; cout<<"Please enter the number to be inserted:"; cin>>num; listinsert_sq(l,place,num); display(l); int place1; cout<<"Please enter the location where the number will be deleted:"; cin>>place1; int num1; cout<<"Please enter the number to be deleted:"; cin>>num1; listdelete_sq(l,place1,num1); display(l); return 0; }
今天也是元气满满的一天,good luck!
标签:tab 线性 span div new realloc length sizeof nbsp
原文地址:http://www.cnblogs.com/cattree/p/7452092.html