zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    1105 Spiral Matrix (25分)(蛇形填数)
    1104 Sum of Number Segments (20分)(long double)
    1026 Table Tennis (30分)(模拟)
    1091 Acute Stroke (30分)(bfs,连通块个数统计)
    1095 Cars on Campus (30分)(排序)
    1098 Insertion or Heap Sort (25分)(堆排序和插入排序)
    堆以及堆排序详解
    1089 Insert or Merge (25分)
    1088 Rational Arithmetic (20分)(模拟)
    1086 Tree Traversals Again (25分)(树的重构与遍历)
  • 原文地址:https://www.cnblogs.com/AKsnoopy/p/7266422.html
Copyright © 2011-2022 走看看