順序棧的操作,整數進棧,取棧頂元素,棧內剩余元素


// main.cpp

//  stack_quhao

//  Created by duanqibo on 2019/6/29.

//  Copyright © 2019年 duanqibo. All rights reserved.

//  順序棧的操作,整數進棧,取棧頂元素,棧內剩余元素

 

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

const int maxsize=6;

/*

 typedef struct student

 {

 int No;

 char name[20];

 char sex[2];

 int age;

 }DataType;

 */

typedef struct seqstack

{

    int data[maxsize];

    int top;

}SeqStk;

//棧初始化

int InitStack(SeqStk *stk)

{

    stk->top=0;

    return 1;

}

//判斷是否顯空棧

int EmptyStack(SeqStk *stk)

{

    if(stk->top==0)

        return 1;

    else

        return 0;

}

//入棧

int Push(SeqStk *stk,int x)

{

    if(stk->top==maxsize-1)

    {

        printf("棧已滿!");

        return 0;

    }

    else

    {

        stk->top++;

        stk->data[stk->top]=x;

        return 1;

    }

}

//出棧

int Pop(SeqStk *stk)

{

    if(EmptyStack(stk))

    {

        printf("棧已空!");

        return 0;

    }

    else

    {

        stk->top--;

        return 1;

    }

}

//取棧頂元素

int GetTop(SeqStk *stk)

{

    if(EmptyStack(stk))

        return 0;

    else

        return stk->data[stk->top];

}

void menu()

{

    printf("*************************\n");

    printf("    1.進棧(-1結束)\n");

    printf("    2.輸出棧頂元素\n");

    printf("    3.剩余棧元素\n");

    printf("    0.退出系統\n");

    printf("*************************\n");

}

int main(int argc, const char * argv[])

{

    SeqStk SK;

    int n;

    int ch;

    InitStack(&SK);

    menu();

    while(1)

    {     

        printf("請輸入:");

        scanf("%d",&ch);

        switch(ch)

        {

            case 1:

                //printf("\n---客戶取號---\n");

                scanf("%d",&n);

                while(n!=-1)

                    //for(i=0;i<6;i++)

                {                  

                    Push(&SK,n);

                    scanf("%d",&n);

                }

                break;

            case 2:

                if(!EmptyStack(&SK))

                {

                    n=GetTop(&SK);

                    Pop(&SK);

                    printf("\n從棧中出來的數是:%d\n",n);

                    break;

                }

                else

                    printf("\n無人等待服務!\n");

                break;

            case 3:

                printf("\n棧中剩余元素...\n");

                while(!EmptyStack(&SK))

                {

                    n=GetTop(&SK);

                    Pop(&SK);

                    printf("\n棧中剩余的元素為 %d!\n",n);

                }

                break;

            case 0:

                exit(1);

                break;                

        }     

    }

}

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM