• 6 线性表-栈-顺序存储


    自己简直是强迫症晚期,上次因为对访问结构体成员该用什么方法困惑了很久,导致没把顺序存储的捣鼓出来(明明比链式的要好写)

    今天花了个20分钟调好了

    因为今天比较晚,赶时间就没给类型起别名用ElemType写,直接用了int类型。需要的话可以自行更改。

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<iostream>
     4 using namespace std;
     5 #define maxsize 50
     6 /*顺序栈的定义*/
     7 typedef struct Snode{
     8 int data[maxsize];
     9 int top;
    10 }SqStack;
    11 /*栈的初始化:设置S.top为1,站顶元素是S.data[top]*/
    12 void InitStack(SqStack *S)
    13 {
    14     (*S).top=-1;
    15 }
    16 /*判断栈是否为空:top==-1*/
    17 int StackEmpty(SqStack *S)
    18 {
    19     if(S->top==-1) return 1;
    20     else return 0;
    21 }
    22 /*入栈*/
    23 int Push(SqStack *S,int x)
    24 {
    25     if(S->top==maxsize-1)//栈满了
    26     return -1;
    27     S->data[++S->top]=x;
    28     /*这里等价于
    29         S->top++;
    30         S->data[S->top]=x;
    31       先指针加一再入栈
    32     */
    33    // cout<<"push the data x:"<<x<<endl;
    34     return 1;
    35 }
    36 /*读取栈顶元素*/
    37 int GetTop(SqStack *S,int &x)
    38 {
    39     if(S->top==-1)//栈空
    40     return -1;
    41     x=S->data[S->top];
    42     return 1;
    43 }
    44 /*出栈*/
    45 int Pop(SqStack *S,int x)
    46 {
    47   if(S->top==-1)
    48     return -1;//栈空,啥也吐不出来
    49   x=S->data[S->top--];
    50 
    51   /*等价于
    52   x=S->data[S->top];
    53   S->top--;
    54   */
    55   return 1;
    56 }
    57 int main()
    58 {
    59     SqStack *S=(SqStack *)malloc(sizeof(SqStack));//一定要先生成一个指针
    60     InitStack(S);
    61     cout<<(*S).top<<endl;
    62     int a1=StackEmpty(S);
    63     cout<<a1<<endl;
    64     cout<<"Test the function 'Push',input a data:";
    65     cin>>a1;
    66     Push(S,a1);
    67     int w;
    68     cout<<"Before GetTop,w is"<<w<<endl;
    69 
    70     GetTop(S,w);
    71     cout<<"After GetTop,w is ";
    72     cout<<w<<endl;
    73     int q=100;
    74     Push(S,q);
    75     GetTop(S,w);
    76     cout<<w<<endl;
    77     cout<<"-------------------------------------"<<endl;
    78     cout<<"Test the function 'Pop':";
    79     Pop(S,w);
    80     cout<<w<<endl;
    81     cout<<"After Pop a data,the top of stack is:";
    82      GetTop(S,w);
    83     cout<<w<<endl;
    84     return 0;
    85 }
  • 相关阅读:
    Ado.net继续学习_人力管理系统开发
    ASP.Net中
    接口实例_模拟简单的播放器解码插件扩展
    JQuery 学习进阶
    android UI进阶之仿iphone的tab效果
    Windows 8 Metro Stype App 学习笔记(五)文件操作
    Windows 8 学习笔记(六)—Accelerormeter和GeoLocation
    mmap如何使用?
    Android自定义组合控件
    Android系列开发博客资源汇总
  • 原文地址:https://www.cnblogs.com/AKsnoopy/p/7266422.html
Copyright © 2020-2023  润新知