Given a string of letters(A-Z),your task is to arrange them in alphabetic order.
Following is an example:
A string "BAC" contains 3 letters B,A and C,you should output
ABC
ACB
BAC
BCA
CAB
CBA
In the output file.
A string may contain several letters same,for example "BBC" you should output like this:
BBC
BCB
CBB
Input
The first line of input contains a single integer t, the number of test cases,followed by the input data for each test data.Each test case is a string of n(1<=n<=26) letters.
Output
You should output Case K: in the first line and the sequences of arrangement in the following lines of each case.
Sample Input
2
BAC
BBC
Sample Output
Case 1:
ABC
ACB
BAC
BCA
CAB
CBA
Case 2:
BBC
BCB
CBB
这道题目,我采用的是递归算法实现的。 采用的链串 结构;
算法简单描述为:对一个链串,有个标记开始置换的指针,然后向后移动,直到末尾,然后置换的指针前移,重复上面的过程。如果标记的指针的内容和移动指针内容不同就打印出来;
源代码如下:
#include <stdio.h>
#include <iostream>
using namespace std ;
typedef struct str
{
char ch ;
struct str * next ;
}str ;
void print(str * s); //打印
void create(str *&s);//建立
void travel(str *&s,str * r) ;//遍历,采用递归算法,实现排列问题
void swap(char &a , char & b) ;//交换
int main(int argc, char* argv[])
{
str * s ;
create(s);
print(s);
travel(s,s->next);
system("PAUSE");
return 0;
}
void create(str *&s)//建立链串
{
s = new str ;
str * p ;
str * q = s ;
char ch ;
while((ch = getchar())!= '/n')
{
p = new str ;
p->ch = ch ;
p->next = NULL ;
q->next = p ;
q = p ;
}
q->next = NULL ;
}
void print(str * s)
{
str * p ;
p = s->next ;
while(p != NULL)
{
cout<<p->ch ;
p = p->next ;
}
putchar('/n');
}
void swap(char &a , char & b)
{
char temp ;
temp = a ;
a = b ;
b = temp ;
}
void travel(str *&s,str * r) //遍历
{
str * p = r;
str * q = p->next ;
if(r->next == NULL)
{
return ;
}
else
{
while(p!= NULL)
{
q = p->next ;
while(q != NULL)
{
swap(p->ch,q->ch);
if(p->ch != q->ch)
{
print(s);
travel(s,p->next);
}
swap(p->ch,q->ch);
q= q->next ;
}
p = p->next ;
}
}
}