將一個順序表實現迴圈左移n個位置後的效果
阿新 • • 發佈:2018-11-05
#include <stdio.h> /* 題目:天勤41頁綜合應用題2 將存放n個整數的順序表迴圈左移P個位置,實現 (X0,X1,...,Xn-1) (Xp,Xp+1,...,Xn-1,X0,X1...,Xp-1) 演算法: 實際的操作並不是對順序表真的進行迴圈左移,而是通過逆序操作,實現了迴圈左移的效果 將子表(X0,X1...,Xp-1)逆序為(Xp-1,...,X1,X0) 將子表(Xp,Xp+1,...,Xn-1)逆序為(Xn-1,...,Xp+1,Xp) 將整張表(Xp-1,...,X1,X0,Xn-1,...,Xp+1,Xp)逆序為(Xp,Xp+1,...,Xn-1,X0,X1...,Xp-1) */ #define maxlen 50 #define DATATYPE int typedef struct{ DATATYPE arr[maxlen]; int length; }Seqlist; void print_SQ(Seqlist list) { for(int i=0;i<list.length;i++){ printf("%d ",list.arr[i]); } printf("\n"); } int main(void) { Seqlist list = {{1,2,3,4,5,6,7,8,9,10},10}; print_SQ(list); int p = 4; int i = 0, j = p-1; int tmp; //將子表(X0,X1...,Xp-1)逆序為(Xp-1,...,X1,X0) while(i < j){ tmp = list.arr[i]; list.arr[i] = list.arr[j]; list.arr[j] = tmp; ++i;--j; } print_SQ(list); //將子表(Xp,Xp+1,...,Xn-1)逆序為(Xn-1,...,Xp+1,Xp) i = p; j = list.length-1; while(i < j){ tmp = list.arr[i]; list.arr[i] = list.arr[j]; list.arr[j] = tmp; ++i;--j; } print_SQ(list); //將整張表(Xp-1,...,X1,X0,Xn-1,...,Xp+1,Xp)逆序為(Xp,Xp+1,...,Xn-1,X0,X1...,Xp-1) i = 0; j = list.length-1; while(i < j){ tmp = list.arr[i]; list.arr[i] = list.arr[j]; list.arr[j] = tmp; ++i;--j; } print_SQ(list); }