问题 A: 左旋转字符串(栈和队列)
题目:
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。
如把字符串abcdef左旋转2位得到字符串cdefab。请实现字符串左旋转的函数。
有多组输入,串的长度不超过100
输入
输入:
abcdef
输出
输出:
cdefab
样例输入 Copy
unbreakable
样例输出 Copy
breakableun
代码实现:
#include<stdio.h>
#define max 1000
typedef struct
{
char data[max];
int top;
} Stack;
/*初始化栈*/
Stack *init_stack()
{
Stack *stack;
stack=(Stack*)malloc(sizeof(Stack));
stack->top=-1;
return stack;
}
/*判断栈是否为空*/
int is_empty(Stack *stack)
{
if(stack->top==-1)
{
printf("栈空");
return 1;
}
return 0;
}
/*判断是否栈满*/
int is_full(Stack *stack)
{
if(stack->top==max-1)
{
printf("栈满");
return 1;
}
return 0;
}
/*进栈*/
void push(Stack *stack,char n)
{
if(!is_full(stack))
{
stack->data[++stack->top]=n;
}
}
/*出栈*/
int pop(Stack *stack)
{
if(is_empty(stack))
return -1;
else
return stack->data[stack->top--];
}
/*打印栈中元素*/
void print_stack(Stack *stack)
{
for(int i=2; i<=stack->top; i++)
printf("%c",stack->data[i]);
for(int j=0; j<=1; j++)
printf("%c",stack->data[j]);
printf("\n");
}
int main()
{
int i,j;
char a[10000];
while(~scanf("%s",a))
{Stack *stack;
stack=init_stack();
for(j=0; a[j]!='\0'; j++) //将字符串压入栈
{
push(stack,a[j]);
}
print_stack(stack);
}
return 0;
}