题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

C 的粗暴实现

#include<stdbool.h>

typedef struct Stack {
	int val;
	struct Stack* next;
}Stack;

int IsEmpty(Stack* S)
{
	if (!S || !(S->next))
		return 1;
	return 0;
}

void push(Stack* S, int v)
{
	Stack* tmp = (Stack*)malloc(sizeof(Stack));
	tmp->val = v;
	tmp->next = S->next;
	S->next = tmp;
}

int pop(Stack* S)
{
	Stack* tmp;
	int tmp_v;
	if (!IsEmpty(S))
	{

		tmp = S->next;
		tmp_v = tmp->val;

		S->next = tmp->next;

		free(tmp);
		tmp = NULL;
		return tmp_v;
	}
	return -1000;
}

int top(Stack* S)
{
	Stack* tmp;
	int tmp_v;
	if (!IsEmpty(S))
	{
		return S->next->val;
	}
	return -1000;
}

bool IsPopOrder(int* pushV, int pushVLen, int* popV, int popVLen ) {
    Stack* head = (Stack*)malloc(sizeof(Stack));
	int* Push = pushV;
	int* Pop = popV;
	int flag = 0;
    
	
	if (pushVLen != popVLen|| pushV==NULL||popV==NULL)
		return false;

	head->next = NULL;
	head->val = -1000;

	while (Pop - popV < popVLen)
	{
		while (IsEmpty(head) || top(head) != *Pop)
		{
			if (Push - pushV >= pushVLen)
				break;
			push(head, *Push);
			Push++;
		}

		if (top(head) != *Pop)
			break;
		pop(head);
		Pop++;
	}
	if (IsEmpty(head) && Pop - popV == popVLen)
		return 1;
    return 0;
}
全部评论

相关推荐

Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
挣K存W养DOG:他真的很中意你,为什么不回他
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务