习题2.2 数组循环左移 (20 分)
本题要求实现一个对数组进行循环左移的简单函数:一个数组a中存有n(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向左移m(≥0)个位置,即将a中的数据由(a0a1⋯an−1)变换为(am⋯an−1a0a1⋯am−1)(最前面的m个数循环移至最后面的m个位置)。如果还需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:
输入第1行给出正整数n(≤100)和整数m(≥0);第2行给出n个整数,其间以空格分隔。
输出格式:
在一行中输出循环左移m位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
8 3
1 2 3 4 5 6 7 8
输出样例:
4 5 6 7 8 1 2 3
1.算法 链表
#include<stdio.h>
#include<stdlib.h>
typedef struct Node *NodePtr;
struct Node
{
int Val;
NodePtr Next;
};
int main()
{
int n, m;
int i;
NodePtr Head,Rear,Tmp,Pre;
Head = Rear = (NodePtr)malloc(sizeof(struct Node));
Head->Next = NULL;
scanf("%d %d",&n, &m);
/*赋值*/
for(i=0; i<n; i++){
Pre = (NodePtr)malloc(sizeof(struct Node));
Pre->Next = NULL;
scanf("%d", &Pre->Val);
Rear->Next = Pre;/* 新结点接到末尾*/
Rear = Pre;/*Rear指针移到末尾*/
}
/*左移 ps:赋值时指针值和指针指向都要赋值*/
for(i=0; i<m; i++){
Tmp = (NodePtr)malloc(sizeof(struct Node));
Tmp->Val = Head->Next->Val;
Tmp->Next = NULL;
Rear->Next = Tmp;
Rear = Tmp;
Head = Head->Next;
}
Tmp = Head->Next;/*一开始一直不理解为什么这句话,后来发现Head指针位置一直未变(Rear=Tmp这句话改变了Rear指针的位置)*/
printf("%d", Tmp->Val);/*格式要求*/
for(Tmp=Tmp->Next; Tmp!=NULL; Tmp=Tmp->Next){
printf(" %d",Tmp->Val);
}
//printf("\n");
system("pause");
return 0;
}
2 翻转算法(思路:前m位翻转,后n-m位翻转,最后全部翻转)
#include<stdio.h>
void turn(int *p , int i , int n );
int main()
{
int n,m;
scanf("%d %d",&n,&m);
if(m>=n)
m=m%n; /*考虑m>n*/
int i,a[n];
for(i=0;i<n;i++)
{
if(i!=n-1)
scanf("%d ",&a[i]);
else
scanf("%d",&a[i]);
} /*这一步其实没必要,普通输入也行*/
turn(a,0,m);
turn(a,m,n+m);
turn(a,0,n);
for(i=0;i<n;i++)
{
if(!i)
printf("%d",a[i]);
else
printf(" %d",a[i]);
}
return 0;
}
void turn(int *p , int i , int n )
{
int tmp;
for(;i<n/2;i++)
{
tmp=*(p+i);
*(p+i)=*(p+n-i-1);
*(p+n-i-1)=tmp;
}
}
拓展(Python的翻转算法)
def ReversalList(list):
l = 0;
r = len(list) - 1;
while(l < r):
list[l], list[r] = list[r], list[l];
l += 1;
r -= 1;
return list;
def LeftReverseList(list, n):
LeftList = ReversalList(list[0 : n]);
RightList = ReversalList(list[n : len(list)]);
return ReversalList(LeftList + RightList);
def LeftReverseListTest(Max):
count = 0;
for i in range(0,Max):
list = [];
for j in range(0,i):
list.append(random.randint(-int(Max / 2), int(Max / 2)));
test = random.randint(0, i);
NewList = LeftReverseList(list, test);
print(test);
print(list);
print(NewList);
if (list != LeftReverseList(NewList, i - test)):
print(list);
print(i, ':error\n');
else:
count += 1;
if (count == Max):
print('allright');
return count;
if __name__ == '__main__':
Max = 10;
LeftReverseListTest(Max);