版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36470920/article/details/76409039
今天开始将持续更新关于C/C++的一个数据结构的博客更新
无奈考研会要求到有一个数据结构神一样的存在,今晚晚上重新回顾了我那不堪回忆的C/C++代码编写,只有一句话可以表达我的感受,那就是:人生苦短,我用python!
不过技多不压身,还是好好学吧,加油!
首先克服了一个程序编译的之后窗口闪退的问题,那就是在程序后面添加一句
system("pause");
今天要实现的算法是将一个数组元素循环左移几位。关于右循环实现实质一样
右循环x位就是左循环n-x位,其中n为数组的长度。
C++代码如下:
#include<iostream>
#define N 50using namespace std;
void Reverse(int R[],int l,int r)
/*函数实现的功能是交换从l到r上的元素,其中l<r先把下标为l上的元素和下标为r上的元素交换,然后
i向后遍历,r向前遍历,直到i和r相等,也即是说这个函数实现的功能是将l到r的元素序列逆序*/
{
int i,j;
int temp;
for(i=l,j=r;i<j;++i,--j)
{
temp=R[i];
R[i]=R[j];
R[j]=temp;//交换元素
}
}
void RCR(int R[],int n,int p)
/*注意参数n是指序列的长度,p是指循环左移的位数这个算法设计思路是先把前p个元素逆序,再把剩下的元素逆序
最后把整个数组逆序*/
{
if(p<=0 || p>=n)//操作前先判断需要左移的位数如果小于0或者大于数组长度就报错
cout<<"Error"<<endl;
else
//当形参正确的时候就执行else语句
{
Reverse(R,0,p-1);
//将第一个元素到第p个元素之间的元素序列逆序
Reverse(R,p,n-1);
//将第p+1个元素到第n个元素之间的序列逆序
Reverse(R,0,n-1);//将整个序列逆序
}
}
int main()
{
int L,i;
int R[N],n;
cout<<"please enter the num you want to move the list:"<<endl;
cin>>L;
cout<<"please enter the len of the list:"<<endl;
cin>>n;
cout<<"enter the elements following:"<<endl;
for(i=0;i<=n-1;++i)
cin>>R[i];
cout<<"the list is:";
for(i=0;i<=n-1;++i)
cout<<R[i]<<" ";
cout<<endl;
RCR(R,n,L);
cout<<"the outcome is :";
for(i=0;i<=n-1;++i)
cout<<R[i]<<" ";
cout<<endl;
system("pause");
}
运行结果:
接下来我用python实现一下:可以好好感受下python的亲切!
#-*-coding:UTF-8-*- l = map(int,raw_input().split()) print 'the list is',l def LeftCirMov(list,n): a = list[:n] a.reverse() b = list[n:] b.reverse() c = a + b c.reverse() print 'the 2 positions looped left shift list is:\n',c LeftCirMov(l,2)结果运行:
the list is [1, 2, 3, 4, 5]
the 2 positions looped left shift list is:
[3, 4, 5, 1, 2]
Process finished with exit code 0