线性表循环右移k位

问题描述:线性表循环右移k位,即:
1 2 3 4 5 6 7 8 9
右移3位后
6 7 8 9 1 2 3 4 5 
#include <iostream>
#include <cstdlib>
using namespace std;
typedef int elemtype;
typedef struct{
 elemtype* elem;
 int listsize;
 int length;
}sqlist;
void create_L(sqlist& L){
 L.elem=(elemtype*)malloc(1000*sizeof(elemtype));
 L.listsize=1000;
 L.length=0;
}
void show(sqlist& L){
 for(int i=0;i<L.length;i++){
  cout<<L.elem[i]<<" ";
 }  
 cout<<endl;
}
 /*先把线性表整体逆置 ,即:9 8 7 6 5 4 3 2 1
然后再把前k+1位逆置(因为数组下标从0开始的),后面的逆置
                                          6 7 8 9,1 2 3 4 5*/
void nixu(sqlist& L,int k){
  for(int i=0;i<L.length/2;i++){
   int t;
   t=L.elem[i];
   L.elem[i]=L.elem[L.length-1-i];
   L.elem[L.length-1-i]=t;  
     }
     for(int i=0;i<k/2;i++)
     {
      int t;
   t=L.elem[i];
   L.elem[i]=L.elem[k-i];
   L.elem[k-i]=t; 
  }
  for(int i=k+1;i<(L.length-1+k+1)/2;i++){
   int t;
   t=L.elem[i];
   L.elem[i]=L.elem[L.length-1+k+1-i];
   L.elem[L.length-1+k+1-i]=t; 
  }
    
 } 
void fuzhi(sqlist& L,int n){
 cout<<"请输入线性表的元素";
 int m;
 for(int i=0;i<n;i++){
  cin>>m;
  L.elem[i]=m;
  L.length++;
 }
}

int main(){
 sqlist l;
 create_L(l);
 fuzhi(l,9); 
 show(l);
 nixu(l,3);
 show(l);
 return 0;
}

猜你喜欢

转载自blog.csdn.net/cyx_chen/article/details/79746570
今日推荐