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

栈的压入、弹出序列

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;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:21
被夸真的超级开心,好可爱的姐姐
码农索隆:老色批们不用脑补了,我把金智妮的图找来了查看图片
点赞 评论 收藏
分享
点赞 评论 收藏
分享
嵐jlu:我是山川🐔里🐔🧱的,阿里系简历全过; 你这简历一看就还是半成品啊,没有荣誉经历奖项什么的吗?
投递阿里巴巴集团等公司8个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务