Design and Implementation of General stack [C implementation]

Source: Internet
Author: User

① Stack Definition [cpp] {void ** base;/* stack bottom */void ** top;/* stack top */int size; /* stack size */} stack_t; the general stack designed here will meet the following requirements: ① data of any data type can be processed. Pay attention to the base and top Data Types in the stack, which are void **, therefore, it can process various data types. ② efficient data operations and access void. ** it is a dual pointer, meaning that the inbound and outbound stacks are only the corresponding data addresses, the data itself does not need to be copied, so it achieves an efficient goal. ② Macro definition to improve stack operation access efficiency, you can use macro definition: [cpp] # define stack_maxsize (stack) (stack-> size) # define stack_isempty (stack) (stack-> top = stack-> base) # define stack_depth (stack) (stack-> top-stack-> base) # define stack_gettop (stack) (stack-> top = stack-> base )? NULL: * (stack-> top-1) ③ operation interface [cpp]/* stack initialization */int stack_init (stack_t * stack, int size) {memset (stack, 0, sizeof (stack_t); stack-> base = (void **) calloc (size, sizeof (void *)); if (NULL = stack-> base) {return-1;} stack-> top = stack-> base; stack-> size = size; return 0 ;} [cpp]/* inbound stack */int stack_push (stack_t * stack, void * node) {if (stack-> top-stack-> base> = stack-> szie) {return-1;} * (stack-> top) = node; stack-> top ++; return 0 ;} [html]/* output stack */int stack_top (stack * stack) {if (stack-> top = stack-> base) {return-1 ;} stack-> top --; * (stack-> top) = NULL; return 0;} [cpp]/* release stack */void stack_free (stack_t * stack) {free (stack-> base); stack-> base = NULL; stack-> top = NULL; stack-> size = 0 ;}

Related Article

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.