栈的创建及POP,PUSH操作

原创
2015/12/16 23:37
阅读数 192
#include<stdlib.h>
#include<iostream>

using namespace std;

typedef struct Node{
  char ch;
  Node * next;
  Node * prior;
}Node,* Bottom,* Top;

//创建栈
Node * createStack()
{
  char str;//int len=0;
  Bottom bottom=(Node *)malloc(sizeof(Node));
  Top top=bottom;
  cin>>str;
  bottom->ch=NULL;
  while(str!='n')
  {
     Node *s=(Node*)malloc(sizeof(Node));
     s->ch=str;
     top->next=s;
     s->prior=top;
     top=top->next;
     cin>>str;
    //len++;
  }
  top->next=NULL;
  return top;
}

//对POP出栈顶元素,并返回栈顶指针
Top pop(Top top)
{
  //ch=top->ch;
  //Node * p=top;
  top=top->prior;
  //free(p);
  return top;
}

//将元素压入栈
void push(Top top,char ch)
{
  Node *s=(Node *)malloc(sizeof(Node));
  s->ch=ch;
  top->next=s;
  s->prior=top;
  top=top->next;
}

//根据后进先出原则读取栈的所有元素
void procOutput(Top top)
{
  while(top->ch!=NULL)
  {
    cout<<top->ch<<" ";
    top=top->prior;
  }
  cout<<"\n";
}

int main()
{
  char _char;
  Top top=createStack();
  top=pop(top);
  procOutput(top);
  cin>>_char;
  push(top,_char);
  procOutput(top);
  return 0;
}
 
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部