题目描述:给你一个特定序列,要求你经过一定的变换规则将升序列变为给的特定序列。
https://vjudge.net/problem/UVA-11925
变换规则为:1.第一个元素和第二个元素交换. 2、首元素到尾部。
题目分析:逆着处理,最后输出的时候倒着输出就行了。若第一个元素大于第二个元素则交换,否则将最后一个元素变为首元素。注意:到第一个元素是n时,不进行交换,否则会出现死循环。找到规则很重要,逆着处理的时候就是交换第一个和第二个,将尾部的元素 移动到第一个。使用循环链表只需要将head前移即可。
这个和题目中的描述是不同的,书上有错误。
另外,这里使用了双向循环链表,和堆栈,程序非常简单。
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <sstream>
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct dnode {
int data;
struct dnode *prior;
struct dnode *next;
} dnode;
dnode *add(dnode *dhead,int x);
dnode *del(dnode *dhead);
void printdnode(dnode *dhead);
dnode *add(dnode *dhead,int x) {
dnode *s=NULL;
dnode *p=NULL;
s=(dnode *)malloc(sizeof(dnode));
s->data=x;
if(NULL==dhead) {
dhead=s;
s->next=s;
s->prior=s;
} else {
p=dhead;
//先找到添加的位置
// while(1) {
// if(s->data>p->data) {
// p=p->next;
// if(p==dhead) {
// break;
// }
// } else {
// break;
// }
// }
//插入到p节点的前面
p->prior->next=s;
s->prior=p->prior;
s->next=p;
p->prior=s;
}
return dhead;
}
dnode *del(dnode *dhead) {
int x=0;
dnode *p=NULL;
if(NULL==dhead) {
printf("dlist empty\n");
return NULL;
}
printf("请输入删除的数据:\n");
scanf("%d",&x);
p=dhead;
//找到需要删除数据的地址
while(1) {
if(p->data==x) {
break;
}
p=p->next;
if(p==dhead) {
printf("no this data in dlist\n");
return dhead;
}
}
if(dhead==p) {
dhead=dhead->next;
}
p->prior->next=p->next;
p->next->prior=p->prior;
if((dhead->next==dhead)&&(dhead->prior=dhead)&&(dhead->data==x)) {
free(dhead);
dhead=NULL;
p=NULL;
} else {
free(p);
p=NULL;
}
return dhead;
}
void printdnode(dnode *dhead) {
if(NULL==dhead) {
printf("dlist empty\n");
return;
}
dnode *p=NULL;
p=dhead;
while(1) {
printf("%d ",p->data);
p=p->next;
if(p==dhead) {
break;
}
}
printf("\n");
}
bool check(dnode *dhead,dnode *tail)
{
dnode *p=dhead;
while(p!=tail)
{
if(p->data>p->next->data)
return false;
p=p->next;
}
return true;
}
int main() {
int n,t;
stack<int> st;
while(scanf("%d", &n)&&n) {
if(n==1){
//printf("\n");
//continue;
}
while(!st.empty()) st.pop();
dnode *dhead=NULL,*tail,p,q;
for(int i=0; i<n; i++) {
cin>>t;
dhead=add(dhead,t);
}
tail=dhead->prior;
while(!check(dhead,tail))
{
if(dhead->data>dhead->next->data&&dhead->data!=n)
{
t=dhead->data;
dhead->data=dhead->next->data;
dhead->next->data=t;
st.push(1);
//printdnode(dhead);
}
if(check( dhead,tail)) break;
else
{
st.push(2);
dhead=tail;
tail=tail->prior;
//printdnode(dhead);
}
}
while(!st.empty())
{
cout<<st.top();
st.pop();
}
cout<<endl;
}
return 0;
}