資料結構-棧(先進後出表)

來源:互聯網
上載者:User

//資料結構-棧(先進後出表)
#include<stdio.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
 ElemType stack[MaxSize];
 int top;
}stacktype;
//初始化棧
void initstack(stacktype *s)
{
  s->top=-1;
}
//入棧
void push(stacktype *s,ElemType x)
{
 if(s->top==MaxSize)
 {
  printf("The stack is full!/n");
 }
 else
 {
  s->top++;
  s->stack[s->top]=x;
 }
}
//出棧
void pop(stacktype *s)
{
 if(s->top==-1)
 {
  printf("The stack is empty!/n");
 }
 else
 {
  s->top--;
 }
}
//取棧頂元素
ElemType gettop(stacktype *s)
{
 if(s->top==-1)
 {
  printf("The stack is empty!/n");
 }
 else
 {
  return(s->stack[s->top]);
 }
}
//顯示棧中元素
void display(stacktype *s)
{
 int i;
 printf("The element in the stack:/n");
 for(i=s->top;i>=0;i--)
 {
  printf("%c/n",s->stack[i]);
 }
 printf("/n");

}
//操作的實現
main()
{
 stacktype *st;
 stacktype s;
 st=&s;
 printf("Init a new stack./n");
 initstack(st);
 printf("Push abc into the stack by turns:/n");
 push(st,'a');
 push(st,'b');
 push(st,'c');
 display(st);
 printf("The first word in the stack is:%c/n",gettop(st));
 printf("Pop one word./n");
 pop(st);
 display(st);

 
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.