数据结构—关于线性表插入元素

  1. <pre class="html" name="code"><img src="https://img-my.csdn.net/uploads/201210/30/1351565091_4900.JPG" alt="">#include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. #define LIST_INIT_SIZE 100 //初始化分配量  
  6.   
  7. #define LISTINCREMENT 10 //存储空间的分配增量  
  8.   
  9.   
  10. typedef int Status;  
  11.   
  12. typedef int ElemType;  
  13.   
  14. typedef struct{  
  15.   
  16.     ElemType *elem;//储存空间基址  
  17.   
  18.     int length;//当前长度  
  19.   
  20.     int listsize;//当前的分配的存储容量 (以sizeof (ElemType)为单位)  
  21. }SqList;  
  22.   
  23. Status InitList_sq(SqList &L){  
  24.   
  25.     L.elem = (ElemType *)malloc(LIST_INIT_SIZE *sizeof(ElemType));  
  26.   
  27.     if ( !L.elem)exit(1);//存储分配失败  
  28.   
  29.     L.length = 0; //空表长度为0  
  30.   
  31.     L.listsize =LIST_INIT_SIZE;//初始储存容量  
  32.   
  33.     return true;  
  34. }  
  35.   
  36.   
  37. Status ListInsert_Sq(SqList &L,int i,ElemType e)      
  38. {      
  39.     //在顺序线性表L中第i个位置之前插入新的元素e        
  40.     //i的合法值为1<=i<=ListLength_Sq(L)+1        
  41.     if(i <1 || i> L.length + 1)      
  42.         return false;   //i值不合法        
  43.     if(L.length >= L.listsize)   //当前存储空间已满,增加分配        
  44.     {      
  45.         ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize + LISTINCREMENT )* sizeof(ElemType));      
  46.         if(!newbase)      
  47.             exit(1);    //存储分配失败        
  48.         L.elem = newbase;//新基址        
  49.         L.listsize += LISTINCREMENT;    //增加存储容量        
  50.     }      
  51.       
  52.     ElemType *q = &(L.elem[i-1]);//q为插入位置        
  53.       
  54.     for(ElemType *p = &(L.elem[L.length-1]);p>=q;--p)      
  55.         *(p+1) = *p;    //插入位置及之后的元素右移        
  56.       
  57.     *q = e;     //插入e        
  58.     ++L.length;     //表长增1     
  59.       
  60.     ElemType l = *q; //用一个自定义的变量 返回指针q中所指代的值  
  61.     return l;      
  62. }     
  63.   
  64. int main()      
  65. {      
  66.     SqList L;      
  67.     
  68.     InitList_sq(L);     
  69.           
  70.     
  71.     ElemType s = ListInsert_Sq(L,1,1234);    
  72.        
  73.     cout << s <<endl;    
  74.     
  75.     
  76.     return 0;      
  77. }    
  78.  </pre><br>  
  79. <pre></pre>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值