《数据结构与算法》- 线性结构复习题 6-1 有序数组的插入 (10 分)

分了几种情况,判满,x是表里最大的数,X是最小的数,x和表里某个数相等了,x在中间。

AC代码:

bool Insert( List L, ElementType X )
{
    
    
    //判满
    if(L->Last+1==MAXSIZE){
    
    
        return false;
    }
     //x最大
    if(L->Data[0]<X){
    
               
      for(int i=L->Last;i>=0;i--){
    
    
               L->Data[i+1]=L->Data[i];
           }
        L->Data[0]=X;
        L->Last++;
      return true;
    }
    //x最小
    if(L->Data[L->Last]>X){
    
              
        L->Data[L->Last+1]=X;
          L->Last++;
          return true;
    }
   //在中间
    for(int i=0;i<L->Last+1;i++){
    
    
        if(L->Data[i]==X){
    
    
            return false;
        }
        while(X<L->Data[i-1] && X>L->Data[i]){
    
    
            int pos=i;
           for(int i=L->Last;i>=pos;i--){
    
    
               L->Data[i+1]=L->Data[i];
           }
             L->Data[pos]=X;
             L->Last++;
            break;
        }
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/guankunkunwd/article/details/122084062