论坛首页 编程语言技术论坛

栈的创建及POP,PUSH操作

浏览 2541 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-06-29  
C
#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;
}
 
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics