Pop Sequence 2013 PAT Spring Exam Zhenti Exam Exam ExaminationTeamのスタックの基本概念

スタックシャッフルをシミュレートします。この図は一般的な考え方です。

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef struct SNode *PtrToSNode;

struct SNode
{
	int Data;
	PtrToSNode Next;
	int Total;
	int MaxSize;
};
typedef PtrToSNode Stack;

Stack CreateStack(int MaxSize)
{
	Stack S;
	S = (Stack)malloc(sizeof(struct SNode));
	S->Total = 0;
	S->Next = NULL;
	S->MaxSize = MaxSize;
	return S;
}

bool IsEmpty(Stack S)
{
	return(S->Next==NULL);
}

bool Push(Stack S,int X)
{	
	if(S->Total<S->MaxSize)
	{
		PtrToSNode TmpCell;
		TmpCell = (PtrToSNode)malloc(sizeof(struct SNode));
		TmpCell->Data = X;
		TmpCell->Next = S->Next;
		S->Next = TmpCell;
		S->Total++;
		return true;
	}
	else
		return false;
}

int Pop(Stack S)
{
	int TopELement;
	PtrToSNode FirstCell;
	if(IsEmpty(S))
		return -1;
	else
	{
		FirstCell = S->Next;
		TopELement = FirstCell->Data;
		S->Next = FirstCell->Next;
		free(FirstCell);
		S->Total--;
		return TopELement;
	}
}

int Top(Stack S)
{
	if(S->Next==NULL) return -1;
	else
		return S->Next->Data;
}

int main()
{
	//Stack A,B,S;
	int M,N,K;
	int i,j,k;//计数用
	scanf("%d %d %d",&M,&N,&K);
	int Permutation[K][N];
	for(i=0;i<K;++i)
	{
		for(j=0;j<N;++j)
		{
			scanf("%d",&Permutation[i][j]);
		}
	}
	//A = CreateStack(N); B = CreateStack(N); S = CreateStack(M);
	/*for(i=N;i>0;--i)
	{
		Push(A,i);
	}*/
	for(i=0;i<K;++i)
	{
		Stack A,B,S;
		A = CreateStack(N); B = CreateStack(N); S = CreateStack(M);
		for(k=N;k>0;--k) Push(A,k);//把1到N推入栈A中
		j = 0;
		while(j<N)
		{
			if(Top(S)!=Permutation[i][j])
			{
				if((S->Total<S->MaxSize)&&(!IsEmpty(A)))
				{
					Push(S,Pop(A));
				}
				else
				{
					printf("NO\n");break;
				}
			}
			else
			{
				Push(B,Pop(S));j++;
			}
		}
		if(j==N) printf("YES\n");
	}
	return 0;
}

 

おすすめ

転載: blog.csdn.net/yiwaite/article/details/95084296