栈-链栈

数据结构-链栈的基本实现

InitlinkStack(SqStack& s) 初始化栈

Empty(SqStack s) 判断栈是否为空

PushStack(SqStack& s) 进栈

PopStack(SqStack& s) 出栈

GetTop(SqStack s) 获取栈顶元素

使用不带头结点

#include <iostream>
using namespace std;
#define ElemType int

typedef struct LNode {
	ElemType data;
	LNode *next; //栈顶位置
}LNode,*LinkStack;

//初始化,时间复杂度O(1)
bool InitLinkStack(LinkStack& L) {
	L = NULL;
	return true;
}
//判断栈是否为空,时间复杂度O(1)
bool Empty(LinkStack L) {
	if (L == NULL) {
		printf("栈空\n");
		return true;
	}
	return false;
}
//入栈,时间复杂度O(1)
bool PushStack(LinkStack& L) {
	LNode *e = new LNode;
	printf("输入进栈元素:");
	scanf("%d", &e->data);
	e->next = L; //第一次入栈L=NULL;
	L = e;		//栈顶结点指针为头指针
	printf("元素%d已入栈!\n", e->data);
	return true;
}
//出栈,时间复杂度O(1)
bool PopStack(LinkStack &L) {
	if (Empty(L)) {
		return false;
	}
	LNode* d = L; //L为栈顶元素
	L = d->next;; 
	printf("元素%d已出栈!\n", d->data);
	return true;
}
//获取栈顶元素,时间复杂度O(1)
bool GetTop(LinkStack L) {
	if (Empty(L)) {
		return false;
	}
	printf("栈顶元素为:%d。\n", L->data);
	return true;
}


void menu()
{
	printf("********1.入栈      2.出栈*********\n");
	printf("********3.取栈顶    4.退出*********\n");
}

int main()
{
	LinkStack L; int choice;
	InitLinkStack(L);
	while (true)
	{
		menu();
		printf("请输入菜单序号:");
		scanf("%d", &choice);
		if (choice == 4) break;
		switch (choice)
		{
		case 1:PushStack(L); break;
		case 2:PopStack(L); break;
		case 3:GetTop(L); break;
		default:printf("输入错误!!!\n");
		}
	}
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值