• 【数据结构】栈 的 顺序表示


     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 
     4 typedef struct SqStack {
     5     int *base;
     6     int *top;
     7     int stacksize;
     8 }SqStack; 
     9 
    10 //创建顺序栈 
    11 SqStack InitStack() {   
    12     SqStack S;
    13     S.base = (int*)malloc(10*sizeof(int));
    14     if(!S.base)
    15     exit(0);
    16     S.top = S.base;
    17     S.stacksize = 10 ;
    18     return S;
    19 }
    20 
    21 //设置为空栈 
    22 int ClearStack(SqStack &S) {
    23     S.top = S.base;
    24     return 0;
    25 }
    26 
    27 //将元素入栈 
    28 int Push(SqStack &S , int e) {
    29     
    30     if(S.top - S.base >= S.stacksize)
    31     {
    32         S.base = (int *)realloc(S.base , (S.stacksize + S.stacksize/2)*sizeof(int));
    33         if(!S.base)
    34         exit(0);
    35         S.top = S.base + S.stacksize ;
    36         S.stacksize += S.stacksize/2 ;
    37     }
    38     *S.top++ = e;
    39 }
    40 
    41 //弹出栈顶元素 
    42 int Pop(SqStack &S) {
    43     if(S.base == S.top)
    44     return 0;
    45     return *--S.top;
    46 }
    47 
    48 //取出栈顶元素 
    49 int GetTop(SqStack &S) {
    50     if(S.base == S.top)
    51     return 0;
    52     return *(S.top-1);
    53 }
    54 
    55 //将栈内元素倒置 
    56 void StackTraverse(SqStack &S) {
    57     SqStack S1 = InitStack();
    58     while(S.base != S.top) 
    59         Push(S1 , Pop(S));
    60     S = S1 ;
    61 }
    62 
    63 //输出所有元素 
    64 int PrintfStack(SqStack &S) {
    65     for( ; ; ) {
    66         if(S.base == S.top)
    67         return 0;
    68         printf("%d" , Pop(S));
    69     }
    70 }
    71 int main() {
    72     SqStack S ;
    73     S = InitStack();
    74     int  n = 0 ;
    75     for(int i = 0 ; i < 2 ; i++)
    76     {
    77         scanf("%d" , &n);
    78         Push(S , n);
    79     }
    80     StackTraverse(S);
    81     PrintfStack(S);
    82 }
  • 相关阅读:
    第十一章关联容器
    第十章泛型算法
    第九章
    第八章
    阅读记录
    java.lang.Class阅读笔记
    java.time包阅读笔记
    CLion运行多个main函数
    c++中lower_bound和upper_bound中的comp参数
    如何写dfs
  • 原文地址:https://www.cnblogs.com/duolaAbao/p/9430770.html
Copyright © 2020-2023  润新知