Use arrays to implement stack Functions

Source: Internet
Author: User

《AlgorithmIntroduction: exercises in the data structure chapter.

 

 

Method 1:

Use static Array

#include <stdio. h> <br/> int ss [10]; // defines an array as a stack <br/> int Top = 0; // define the stack pointer <br/> bool stack_empty () // determine whether the stack is empty <br/>{< br/> If (Top = 0) <br/> return true; <br/> else <br/> return false; <br/>}< br/> void push (int * s, int X) // stack entry operation <br/>{< br/> Top = Top + 1; <br/> S [Top] = X; <br/>}< br/> int POP (int * s) // stack exit Operation <br/> {<br/> If (stack_empty ()) // If the stack is empty, return- 1 <br/> return-1; <br/> else // If the stack is not empty, the pointer moves forward by 1, returns the element pointed to by the current pointer <br/> Top = Top-1; <br/> return s [top + 1]; <br/>}< br/> void main () <br/> {<br/> // press the stack consecutively and store the stack 1, 2, 3, 4, and 5 at a time. <Br/> push (SS, 1); <br/> push (SS, 2); <br/> push (SS, 3 ); <br/> push (SS, 4); <br/> push (SS, 5); <br/> while (top! = 0) // If the stack is not empty, the stack operation is performed and the elements of the stack are output. <Br/>{< br/> int P = POP (SS); <br/> printf ("% d/N", P ); <br/>}

 

Method 2:

By passing an array reference

# Include <stdio. h> <br/> bool stack_empty (Int & Top) <br/>{< br/> If (Top = 0) <br/> return true; <br/> else <br/> return false; <br/>}< br/> void push (int * s, int X, Int & top) <br/>{< br/> Top = Top + 1; <br/> S [Top] = X; <br/>}< br/> int POP (int * s, Int & Top) <br/>{< br/> If (stack_empty (top )) <br/> return-1; <br/> else <br/> Top = Top-1; <br/> return s [top + 1]; <br/>}< br/> void main () <br/>{< br/> int ss [10]; <br/> int Top = 0; < Br/> push (SS, 1, top); <br/> push (SS, 2, top); <br/> push (SS, 3, top ); <br/> push (SS, 4, top); <br/> push (SS, 5, top); <br/> while (top! = 0) <br/>{< br/> int P = POP (SS, top); <br/> printf ("% d/N", P ); <br/>}< br/> // printf ("Hello world! /N "); <br/>} 

 

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.