线性表中插入元素
2011-08-30 21:05 javaspring 阅读(478) 评论(0) 编辑 收藏 举报算法2.4.写这个算法花了很长一段时间,唉,看来对线性表还是不够理解,继续努力,下面是代码
#include <iostream> using namespace std; #define maxsize 10 #define sizeincrement 5 typedef int elemtype; typedef struct { elemtype *elem; elemtype aa[maxsize]; int length; int listsize; }sqlist; int main() { sqlist *la,*newbase; int *p,*q; int i,len,pos,value; la=(sqlist *)malloc(maxsize *sizeof(sqlist)); cout<<"链表a的长度"<<endl; cin>>len; cout<<"输入元素"<<endl; for(i=0;i<len;++i) cin>>la->aa[i]; cout<<"输入插入的元素和位置"<<endl; cin>>value>>pos; if(pos<1||pos>len) cout<<"错误"<<endl; if(len>maxsize) { newbase=(sqlist *)realloc(la->elem,(maxsize+sizeincrement) *sizeof(sqlist)); if(!newbase) {cout<<"内存分配失败"<<endl;return 0;} la=newbase; } la->listsize=len-1; q=&(la->aa[pos-1]); for(p=&(la->aa[la->listsize]);p>=q;--p) {//cout<<*(p+1)<<endl; //cout<<*p<<endl; *(p+1)=*p;} *q=value; ++la->listsize; for(i=0;i<=la->listsize;++i) cout<<la->aa[i]<<" "; cout<<endl; return 0; }