Introduction to algorithms ------------ stack simple array implementation

Source: Internet
Author: User

Introduction to algorithms ------------ stack simple array implementation

Stacks and queues are both dynamic sets, and inbound and outbound elements are well defined. Stack rule elements are first-in-first-out (FILO) and queue rule elements are first-in-first-out (FIFO ). Stack and queue implementations can be implemented using arrays and linked lists. See http://www.cplusplus.com/reference /.

The basic operations of the stack include push and pop. The stack has a top pointer, pointing to the latest elements such as the stack, both the inbound and outbound operations are performed from the top of the stack.

The basic operations of the queue include enqueue and dequeue. The queue includes head and tail pointers. Elements always exit from the head of the team and enter from the end of the team. When queues are implemented using arrays, the queue space can be used cyclically to make proper use of space.


Stack's simple array implementation:

# Include
 
  
Using namespace std; struct stack {int * s; int stackSize; int top ;}; // init stackvoid init_stack (stack * s) {s-> stackSize = 100; s-> s = (int *) malloc (sizeof (int) * s-> stackSize); // s-> s = new int (); s-> top =-1;} int stack_empty (stack s) {return (0 = s. stackSize )? 1: 0);} void push_stack (stack * s, int x) {if (s-> top = s-> stackSize) cout <"up to overflow" <endl; else {s-> top ++; s-> s [s-> top] = x; s-> stackSize ++ ;}} void pop_stack (stack * s) {if (0 = s-> stackSize) cout <"down to overflow" <endl; else {s-> top --; s-> stackSize -- ;}} int top_stack (stack s) {return s. s [s. top] ;}int main () {stack s; init_stack (& s); for (int I = 0; I <88; I ++) {push_stack (& s, i) ;}for (int I = 0; I <5; I ++) {cout <
  <<" ";pop_stack(&s);}}< pre>
   
The simple implementation of the queue is written next time. After studying for one night, I am very tired.

<<">

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.