剑指offer面试题31:栈的压入,弹出序列

题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列。假设压入栈的所有数组均不相等。例如:序列{1,2,3,4,5}是某栈的压栈序列,序列{4,5,3,2,1}是该压栈序列的一个弹出序列,但{4,5,3,1,2}就不可能是该压栈序列的弹出序列。

思路:建立一个辅助栈,规律如下:如果下个弹出的数字是栈顶数字,那么直接弹出;如果下个弹出的数字不在栈顶,直到把下个需要弹出的数字压入栈顶为止;如果数字都压入栈后仍然没有找到下个弹出数字,则该序列不是一个弹出序列。

#define STACK_SIZE 1024
typedef struct Stack
{
	int base;
	int top;
	int data[STACK_SIZE]; // 暂不考虑溢出情况
}mystack;

void push(int val) {
	return;
}
int pop() {
	return 0;
}
int top() {
	return 0;
}
bool isempty() {
	return false;
}

mystack help_stack;
// pop , push , top , isempty 函数不实现,只实现逻辑
bool IsPopOrder(const int *pPush, const int *pPop, int length) {
	bool ispoporder = false;
	if (NULL != pPush && NULL != pPop && length > 0) { // 入参检查
		const int *nextpush = pPush;
		const int *nextpop = pPop;
		int length1 = length;
		int length2 = length;
		while (length2 > 0) {
			
			while (true == isempty() || top() != *nextpop) {  // 如果下个弹出的数字不在栈顶,直到把下个需要弹出的数字压入栈顶为止
				if (length1 == 0) {
					break;
				}
				push(*nextpush);
				length1--;
				nextpush++;
			}
			if (top() != *nextpop) {
				break;  //如果数字都压入栈后仍然没有找到下个弹出数字,则该序列不是一个弹出序列
			}

			// equal  如果下个弹出的数字是栈顶数字,那么直接弹出
			pop();
			length2--;
			nextpop++;
		}
		if (length2 == 0 && true == isempty()) {  ////如果数字都压入栈后仍然没有找到下个弹出数字,则该序列不是一个弹出序列
			ispoporder = true;
			return ispoporder;
		}
	}
	return ispoporder;
}


猜你喜欢

转载自blog.csdn.net/qq_34595352/article/details/87278594