链表实现的栈操作

来源:互联网 发布:android网络通信 编辑:程序博客网 时间:2024/04/28 09:32

#include <iostream>
using namespace std;

/* 定义ElemType为int类型 */
typedef int ElemType;
#define TRUE 1
#define FALSE 0
#define NULL 0
#define flag -1


typedef struct StackNode
{ElemType data;
struct StackNode *next;
}StackNode,*LinkedStack;


//初始化
LinkedStack LinkedStackInit()
{LinkedStack top;
top=NULL;
return top;
}

 

//判空栈
 int LinkedStackEmpty(LinkedStack top)
 {if(top==NULL) return TRUE;
 else return FALSE;
 }


 //入栈
 LinkedStack LinkedStackPush(LinkedStack top,ElemType x)
 {LinkedStack s=new StackNode;
 s->data=x;
 s->next=top;
 top=s;
 return top;
 }

 //出栈
 LinkedStack LinkedStackPop(LinkedStack top)
 {if(top!=NULL)
  {ElemType x=top->data;
      cout<<"出栈元素为:"<<x<<endl;
  LinkedStack p;
  p=top;
  top=top->next;
  delete (p);
 }
  return top;
 }


 //取栈顶元素
ElemType LinkedStackTop(LinkedStack top)
{if(top!=NULL)
 return top->data;
}

 

int scan()
{
 int d;
 cout<<"请选择要进行的操作/n";
 cout<<"1.初始化 2.判空栈   3.入栈   4.出栈  5取栈顶元素    /n";
 cout<<"其他键退出。。。。。/n";
 cin>>d;
 return(d);
}

int main()
{
 int quit=0;
ElemType e,i,j;
LinkedStack top;
while(!quit)
{switch(scan())
 {case 1:top=LinkedStackInit();cout<<"/n";break;
 case 2:if(LinkedStackEmpty(top))   cout<<"链栈为空/n";else cout<<"链栈非空/n";break;
 case 3:cout<<"输入入栈元素:/n";
   cin>>e;
   top=LinkedStackPush(top,e);
   break;
 case 4:if(top==NULL)
      cout<<"栈为空!"<<endl;
  else top=LinkedStackPop(top);
   break;
 case 5:if(top==NULL)
      cout<<"栈为空!"<<endl;
  else {j=LinkedStackTop(top);
   cout<<"栈顶元素为:"<<j<<endl;
  }
  break;
  default:quit=1;
  }
}
 return 0;
}

原创粉丝点击