赞
踩
- //链栈LinkStack(带头结点)
-
- #include<stdio.h>
- #include <stdlib.h>
-
-
- typedef int ElemType;
- typedef struct LNode {
- ElemType data; //数据域
- struct LNode *next; //指针域
- }LNode, *LinkStack; //栈类型定义
-
- //1.初始化顺序栈
- void InitStack(LinkStack& s){
- // 创建头节点
- s=(LinkStack)malloc(sizeof(LNode));
- s->next=NULL;
- }
-
- //2.判断是否栈空
- bool StackEmpty(LinkStack s){
- if(s->next==NULL){
- return true;
- }
- return false;
- }
-
- //3.x进栈
- bool Push(LinkStack& s,ElemType x){
- //不必判满,因为链栈没有长度限制,直接创建新结点并赋值
- LNode* p=(LNode*) malloc(sizeof(LNode));
- p->data=x;
- p->next=s->next;
- s->next=p;
- return true;
- }
-
-
- //4.出栈
- bool Pop(LinkStack& s,ElemType& x){
- if(s->next==NULL){ //栈判空
- return false;
- }
- x=s->next->data; //给引用类型x赋值栈顶元素data
- //删除栈顶结点
- LNode *q=s->next; //栈顶元素指针赋值给待删除指针q
- s->next=s->next->next;
- free(q); //释放q所指向的栈顶元素
- return true;
- }
-
-
- //5.读栈顶元素
- bool GetTop(LinkStack s,ElemType& y){
- if(s->next==NULL){
- return false;
- }
- y=s->next->data;
- return true;
- }
-
-
-
- int main() {
-
-
-
- LinkStack s; //s指向头节点,s->next为栈顶指针
-
- //1.初始化一个空栈
- InitStack(s);
-
- //2.判断是否栈空
- if(StackEmpty(s)){
- printf("栈为空!\n");
- }else{
- printf("栈不为空!\n");
- }
-
- //3.x进栈
- if(Push(s,1)){
- printf("进栈成功!\n");
- }else{
- printf("进栈失败!\n");
- }
-
- if(Push(s,2)){
- printf("进栈成功!\n");
- }else{
- printf("进栈失败!\n");
- }
-
- if(Push(s,3)){
- printf("进栈成功!\n");
- }else{
- printf("进栈失败!\n");
- }
-
- //4.出栈
- int x;
- if(Pop(s,x)){
- printf("出栈成功!出栈元素为%d\n",x);
- }else{
- printf("出栈失败!\n");
- }
-
- //5.读栈顶元素
- int y;
- if(GetTop(s,y)){
- printf("栈顶元素y为%d\n",y);
- }else{
- printf("读栈顶元素失败!\n");
- }
-
-
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。