标签:栈-判断
【题目】
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二序列是否为第一个栈的出栈序列,假设入栈所有数字各不相等,例如:
入栈序列{1,2,3,4,5}
出栈序列1{4,5,3,2,1}
出栈序列2{4,3,5,1,2}
出栈序列1是入栈序列的其中一个弹出结果,序列2不是。
【分析】
弹出序列第一个为4,所以要让栈顶元素为4时弹出,所以压入1,2,3,直到4出现在栈顶,序列1第二个为5,说明栈顶要有5存在才行,没有,继续压入5,然后弹出,此时数据栈里是1,2,3,弹出序列1第三个为3,所以直接弹出3,2,1,可以弹出序列1,而序列2中,先是压入1,2,3,4,后弹出4,3,压入5,弹出5,再次弹出时是2,1的顺序,序列2不符合,所以,序列2不是出栈序列之一。
【测试代码】
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define MAX 10
typedef int my_data;
typedef int Stack_data;
typedef struct StackNode
{
Stack_data data;
struct StackNode *next;
}my_stack, * my_stack_ptr;
typedef struct LinkStack
{
my_stack_ptr top;//栈顶是一个指针
int count;
}LinkStack;
void init(LinkStack *s)
{
my_stack_ptr first = (my_stack_ptr)malloc(sizeof(my_stack));
first->next = NULL;
s->top = first;
s->count = 0;
}
int stack_empty( LinkStack *s )
{
if(s->top->next==NULL)
return OK;
else
return ERROR;
}
int push(LinkStack *s, my_data *e)
{
my_stack_ptr pnew = (my_stack_ptr )malloc(sizeof(my_stack ));
pnew ->data = *e;
pnew-> next = s ->top;
s->top = pnew;
s->count++;
return OK;
}
int pop(LinkStack *s , my_data *e)
{
my_stack_ptr p;
if(stack_empty(s))
return ERROR;
*e = s->top->data;
p = s->top;
s->top = s->top->next;
free(p);
s->count --;
return OK;
}
int test(int *in, int *out, int length)
{
if(in == NULL || out == NULL)
return 0;
LinkStack *s= (LinkStack *)malloc(sizeof(LinkStack));
my_data *e = (my_data *)malloc(sizeof(my_data));
init(s);
int i = 0;
int j = 0;
while(j<length)
{
while(stack_empty(s )||s->top->data != out[j]&& i<length)
{
push(s, &in[i] );
++i;
}
if(s->top->data == out[j])
{
pop(s,e);
++j;
}
else
return 0;
}
return 1;
}
void main()
{
LinkStack *s= (LinkStack *)malloc(sizeof(LinkStack));
my_data *e = (my_data *)malloc(sizeof(my_data));
int sequence_in[] = {1,2,3,4,5};
int sequence_out1[] = {4,5,3,2,1};
int sequence_out2[] = {4,3,5,1,2};
if(test(sequence_in, sequence_out1,5))
printf("{4,5,3,2,1}是{1,2,3,4,5}弹出序列之一\n");
else
printf("{4,5,3,2,1}不是{1,2,3,4,5}弹出序列之一\n");
if(test(sequence_in, sequence_out2,5))
printf("{4,3,5,1,2}是{1,2,3,4,5}弹出序列之一\n");
else
printf("{4,3,5,1,2}不是{1,2,3,4,5}弹出序列之一\n");
}
【输出结果】
标签:栈-判断
原文地址:http://blog.csdn.net/xinyu913/article/details/46624277