在顺序线性表第i个元素前插入1个元素的算法,书中代码为:Status ListInsert_Sq(Sqlist &L,int i,ElemType e) { if (iL.length 1) return Error; //i值不合法 if (L.length&
在顺序线性表第i个元素前插入1个元素的算法,书中代码为:Status ListInsert_Sq(Sqlist &L,int i,ElemType e) { if (iL.length 1) return Error; //i值不合法 if (L.length>=L.listsize) { //当前存储空间已满,增加分配 newbase=(ElemType *)malloc (L.elem, (L.listsize ListIncrement)*sizeof(ElemType)); // A if(!newbase) exit (OVERFLOW); //存储分配失败 L.elem=newbase; L.listsize =ListIncrement; } q=&(L.elem[i-1]); //q为插入位置 for (p=&(L.elem[L.length-1]); p>=q;--p) // B { *(p 1)=*p; } //插入位置及之后的元素右移 *q=e; //插入e L.length; //表长加1 return OK;} 关于以上程序:1、代码A段malloc (L.elem, (L.listsize ListIncrement)*sizeof(ElemType));是否可以改为malloc ((L.listsize ListIncrement)*sizeof(ElemType));原因?此处加了L.elem的用意是什么?2、增加分配的代码段如何保证增加ListIncrement后空间一定足够?3、代码B段循环 for (p=&(L.elem[L.length-1]); p>=q;--p) 是从当前表最后一个元素开始,直至当前表第i个元素,依次往后顺延;那为什么起始句为L.elem[L.length-1],最后一个元素不是L.elem[L.length]么?同样的疑问,须移动的结束元素不是应该为L.elem[i]么?而循环中为q,即L.elem[i-1]?4、这里循环代码段为什么不按常规增序来循环,是减序有什么作用或好处么?增序的写法:for(p=&L.elem[i];p<=&L.elem[L.length]; p) { *(p 1)=*p;} 是否也没问题?
展开
全部