Array implementation Stack

Source: Internet
Author: User

  The stack is an important data structure with different implementations, and the program demonstrates how to implement simple stack operations with arrays.

To define a header file:

1#include <stdio.h>2#include <stdlib.h>3 #defineMax_size 104 intStack[max_size];5 inttop=-1; 6 7 voidPushintelement);8 intpop ();9 intisEmpty ();Ten intisfull (); One voidstackfull (); A voidstackempty (); - voidPrintintStack[]);

Into the stack operation:

1 void push (int  element) {2     if(Isfull ()) {3          4      5     stack[++top]=6 }

The stack operation:

1 int pop () {2     if (IsEmpty ()) {3        4    }5     return stack[top--6

Determine if the stack is full:

1 int Isfull () {2     if (top==max_size-1) 3         return 1 ; 4     return 0  5 }

Determine if the stack is empty:

1 int IsEmpty () {2     if (top<0) 3         return 1 ; 4     return 0 ; 5

Is the operation when the stack is full and the stack is empty:

1 voidStackfull () {2fprintf (stderr,"stack is full,cannot push more!"); 3 exit (exit_failure);4 } 5 voidStackempty () {6fprintf (stderr,"Stack is empty,cannot pop more!"); 7 exit (exit_failure);8}

Print all the stack elements (the elements in all stacks will not exist after printing!) ):

1 void print (int  stack[]) {2while     (!  IsEmpty ()) {3         printf ("%4d", Pop ()); 4      5

Main function test:

1 intMainvoid)2 {3     inti;4      for(i=0;i<Ten; i++){ 5Push (i+1);6     }7 pop ();8 pop ();9 print (stack);Ten pop (); One     return 0;  A}

Array implementation Stack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.