棧的建立及POP,PUSH操做

#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;
}
 
相關文章
相關標籤/搜索