Basic operations on dynamic Stack

Source: Internet
Author: User
# Include <stdio. h>
# Include <malloc. h>
# Define error 0
# Define OK 1
# Define stack_int_size 10/* initial storage space allocation */
# Define stackincrement 5/* increment storage space allocation */
Typedef int elemtype;/* define the element type */
Typedef struct {
Elemtype * base;
Elemtype * top;
Int stacksize;/* currently allocated storage space */
} Sqstack;


Int initstack (sqstack * s);/* construct an empty stack */
Int push (sqstack * s, elemtype E);/* inbound stack */
Int POP (sqstack * s, elemtype * E);/* output stack */
Int createstack (sqstack * s);/* Create stack */
Void printstack (sqstack * s);/* outputs the stack and outputs the elements in the stack */


Int initstack (sqstack * s ){
S-> base = (elemtype *) malloc (stack_int_size + stackincrement) * sizeof (elemtype ));
If (! S-> base) return error;
S-> Top = s-> base;
S-> stacksize = stack_int_size;
Return OK;
}/* Initstack */


Int push (sqstack * s, elemtype E)
{
If (S-> top-S-> base> = s-> stacksize)
{
S-> base = (elemtype *) realloc (S-> base, (S-> stacksize + stack_int_size) * sizeof (elemtype ));
If (! S-> Base)
Return Error;
S-> Top = s-> base + S-> stacksize;
S-> stacksize = s-> stacksize + stackincrement;
}
* (S-> top) = E;
S-> top ++;
Return OK;
}/* Push */


Int POP (sqstack * s, elemtype * E)
{
If (S-> top <= s-> base)
Return Error;
* E = * (-- (S-> top ));
// S-> top --;
Return OK;
}/* Pop */


Int createstack (sqstack * s ){
Int E;
If (initstack (s ))
Printf ("init success! \ N ");
Else {
Printf ("init fail! \ N ");
Return Error;
}
Printf ("input data :( terminated by inputing a character) \ n ");
While (scanf ("% d", & E ))
Push (S, e );
Return OK;
}/* Createstack */


Void printstack (sqstack * s)
{
Int E;
While (POP (S, & E ))
Printf ("% 3d", e );
}/* Pop_and_print */


Int main (){
Sqstack SS;
Printf ("\ n1-createStack \ n ");
Createstack (& SS );
Printf ("n2-Pop & Print \ n ");
Printstack (& SS );
Return 0;
}

Basic operations on dynamic 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.