数据结构—顺序表的插入算法

本文详细介绍了顺序存储线性表的插入算法实现过程,并通过C++代码示例演示了如何在指定位置插入新元素,包括异常处理及动态调整表长度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 


 
  1. /*ListInsert(*L,i,e):在线性表L中的第i个位置插入新元素e,L的长度加1*/ 
  2. /* 
  3. 顺序存储线性表的插入算法思路: 
  4. 1。如果插入的位置不合理,抛出异常 
  5. 2。如果线性表的长度大于数组的长度,则抛出异常或动态增加容量 
  6. 3。从最后一个元素开始向前遍历到第i个位置,分别将他们都向后移动一个位置 
  7. 4。将要插入元素填入位置i处 
  8. 5。表长加1 
  9. */ 
  10.   
  11. #include <iostream> 
  12. using namespace std; 
  13. typedef int datatype; 
  14.   
  15. /*顺序线性表的存储结构*/ 
  16. #define MAXSIZE 100 
  17. typedef struct 
  18.     datatype data[MAXSIZE]; 
  19.     int len; 
  20. }SequenList; 
  21.   
  22.  int insert(SequenList *L,int i,int e) 
  23. {  
  24.     int j; 
  25.     if (i < 1 || i > L->len+1 || L->len >= MAXSIZE) /*判断位置i是否存在以及是否有空的*/ 
  26.     {    
  27.         printf( "Error");                   /*存储单元*/ 
  28.     } 
  29.     else 
  30.     {    
  31.         /*for(j=(*L).len-1;j>=i-1;j--)*/ 
  32.             for(j=L->len-1;j>=i-1;j--) 
  33.                 { 
  34.             /*将要插入位置后数据元素向后移一位 */    
  35.             L->data[j+1]=L->data[j];  
  36.         } 
  37.             L->data[i-1]=e; /*将新元素插入*/ 
  38.             L->len=L->len+1; 
  39.        } 
  40.     return 0; 
  41.      
  42. int main(void
  43.     int i,InsertData,InsertLocation; 
  44.     SequenList List; 
  45.         List.len=0;//终端节点下标 
  46.     for(i=0;i<5;i++) 
  47.     {   /*随机生成5个数*/ 
  48.         List.data[i]=rand()%10; 
  49.         List.len++; 
  50.          
  51.         cout<<List.data[i]<<"  "; } 
  52.         cout<<endl; 
  53.         cout<<"输入要添加的数据:"
  54.         cin>>InsertData; 
  55.             cout<<"输入要添加的位置:"
  56.         cin>>InsertLocation; 
  57.         insert(&List,InsertData,InsertLocation); 
  58.             for(i=0;i<List.len;i++) 
  59.             {    
  60.             cout<<List.data[i]<<"  "
  61.             } 
  62.         /* 暂停一会,也可以使用system("pause") */ 
  63.                   getchar(); 
  64.                   getchar(); 
  65.         cout<<endl; 
  66.   
  67.         return 0; 
  68.   
  69.  } 
  Microsoft Visual C++ 6.0 下运行成功。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值