设计一个栈,设计一个max()函数,求当前栈中的最大元素

#include <iostream>
using namespace std;
#define MAXSIZE 256
typedef struct stack
{
    int top;
    int stack[MAXSIZE];
}Stack;
void initStack(Stack *s)
{
    s->top=0;
}

void push(Stack *s,int elem)
{
     if(s->top>MAXSIZE)
         cout<<"stack is full"<<endl;
     s->top++;
     s->stack[s->top]=elem;
}
void pop(Stack *s)
{
    if(s->top<=0)
      cout<<"stack is empty"<<endl;
     s->top--;
}
int max(Stack s)
{
       int maxNum;
       int temp;
       maxNum=s.stack[s.top];
       s.top--;
       cout<<maxNum<<endl;
       while(s.top>0)
         {
             temp=s.stack[s.top];
             cout<<temp<<endl;
             if(temp>maxNum)
                 maxNum=temp;
             pop(&s);
         }
       return maxNum;
}

int main()
{
     Stack s;
     int arr[]={3,6,1,8,12,5,9,21};
     initStack(&s);  //初始化栈
     for(int i=0;i<8;i++)            //入栈
        {
           push(&s,arr[i]);
        }
     cout<<"当前栈中最大元素为:"<<max(s)<<endl;
     return 0;
}

原文地址:https://www.cnblogs.com/xshang/p/3364224.html