<4>Stack栈  链式存储 实现

//
// Stack.h
// Algorithms&Data_structures
//
// Created by TTc on 15-2-2.
// Copyright (c) 2015年 TTc. All rights reserved.
//

#ifndef __Algorithms_Data_structures__Stack__
#define __Algorithms_Data_structures__Stack__

#include <stdlib.h>
#include "list.h"

/* Implement stacks as linked lists .*/
typedef List Stack;

/* Public Interface */
#define stack_init list_init

#define stack_destroy list_destroy


int stack_push(Stack *stack,const void*data);

int stack_pop(Stack *stack, void **data);

#define stack_peek(stack)    ((stack)->head == NULL ? NULL:(stack)->head->data)

#define stack_size list_size

#endif /* defined(__Algorithms_Data_structures__Stack__) */
//
// Stack.c
// Algorithms&Data_structures
//
// Created by TTc on 15-2-2.
// Copyright (c) 2015年 TTc. All rights reserved.
//

#include "stack.h"
#include <stdio.h>
#include <string.h>

int
stack_push(Stack *stack,const void*data){
    // Push the data onto the stack
    return list_ins_next(stack, NULL, data);
}

int
stack_pop(Stack *stack, void **data){
    // Pop the data off the stack
    return list_rem_next(stack, NULL, data);
}
//
// test_stack_main.c
// 
//
// Created by TTc on 15/5/25.
//
//
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "list.h"
#include "stack.h"

/* destroy */
void
destroy(void *data)
{
    printf("in destroy\n");
    free(data);
    return;
}


/* main */
int
main(int argc, char **argv)
{
    Stack stack;
    int *int_ptr = NULL;
    int ret = 0;
    int i;

    stack_init(&stack, destroy);

    for(i = 0; i < 5; i++ )
    {
        int_ptr = (int *)malloc(sizeof(int));
        if( int_ptr == NULL )
            return -1;

        *int_ptr = i;
        printf("push the data: %d\n",i);
        ret = stack_push(&stack, (void *)int_ptr);
        if( ret != 0 )
            return -1;
    }

    printf("size of the stack is : %d\n", stack_size(&stack));

    //pop the data from top to the bottom

    for(i = stack_size(&stack); i > 0; i-- )
    {
        int_ptr = NULL;
        stack_pop(&stack, (void **)&int_ptr);
        printf("i = %d, pop the data = %d\n",i,*int_ptr);
        free(int_ptr);
    }

    printf("after pop size of the stack is :%d\n", stack_size(&stack));
    return 0;
}

你可能感兴趣的:(<4>Stack栈  链式存储 实现)