• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

栈

栈是一个种特殊的线性表,它只能在栈顶进行插入和删除操作,它实现的是一种后进先出(LIFO)的策略。

可以用数组来作为栈,插入操作称为push,删除操作称为pop,栈有个属性top[S],它指向最近插入的元素,称为栈顶,例如栈S包含元素S[1..top[S]],其中S[1]是栈底元素,S[top[S]]是栈顶元素。

当top[S]=0时,栈不包含任何元素,称为空栈,判断空栈过程如下:

STACK-EMPTY(S)
    if top[S] = 0
        then return TRUE
        else return FALSE

c代码为:

int stack_empty(int S[])
{
	if (top == 0) {
		return 1;
	}

	return 0;
}


压栈过程如下:

PUSH(S, x)
    top[S] <-- top[S]+1
    S[top[S]] <-- x

c代码为:

void push(int S[], int x)
{
	S[top++] = x;
}


出栈过程如下:

POP(S)
    if STACK-EMPTY(S)
        then error "underflow"
    else top[S] <-- top[S]-1
        return S[top[S]+1]

c代码为:

int pop(int S[])
{
	if (stack_empty(S)) {
		printf("underflow.\n");
	} else {
		return S[top--];
	}
}
posted @ 2013-08-26 19:22  Class Xman  阅读(194)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3