很好的一道栈与链表的题目,链表直接用数组实现,代码还算清晰吧,注释具体看代码吧。
#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
int nSize;
struct String{
char face[3];
};
struct Pile{
stack<String>face;
}arr[100];
int prev[100],next[100];
void DelGap(){//clear the empty gap
int i,j;
for(i = 0;i != nSize;i = next[i]){
if(arr[i].face.empty()){
next[prev[i]] = next[i];//把当前i的prev的next指向当前i的next
prev[next[i]] = prev[i];
}
}
}
bool Move(){//the operation of move
int cnt = 1;
for(int i = next[0];i != nSize;i = next[i],++cnt){
int last3,last1;
if(cnt > 2){
//if present position is equal or above 3,judge to move 3 positions
last3 = prev[prev[prev[i]]];
if(arr[i].face.top().face[0] == arr[last3].face.top().face[0]
||arr[i].face.top().face[1] == arr[last3].face.top().face[1]){
arr[last3].face.push(arr[i].face.top());
arr[i].face.pop();
return true;
}
}
//else judge to move 1 position
last1 = prev[i];
if(arr[i].face.top().face[0] == arr[last1].face.top().face[0]
||arr[i].face.top().face[1] == arr[last1].face.top().face[1]){
arr[last1].face.push(arr[i].face.top());
arr[i].face.pop();
return true;
}
}
return false;
}
void Solve(){
while(Move())
DelGap();
}
int main()
{
nSize = 0;
String temp;
while(scanf("%s",temp.face) == 1)
{
if(temp.face[0] == '#') break;
while(!arr[nSize].face.empty())
arr[nSize].face.pop();
arr[nSize].face.push(temp);
prev[nSize] = nSize - 1;
next[nSize] = nSize + 1;
++nSize;
if(nSize == 52){
Solve();
int num = 0;
for(int i = 0;i != nSize;i = next[i])
++num;
if(num == 1) printf("1 pile remaining: ");
else printf("%d piles remaining: ",num);
for(int i = 0;i != nSize;i = next[i]){
if(i) printf(" ");
printf("%d",arr[i].face.size());
}
printf("\n");
nSize = 0;
}
}
return 0;
}