Stack栈  链式存储 实现

来源:互联网 发布:诺基亚按键机java游戏 编辑:程序博客网 时间:2024/05/29 02:18
////  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_destroyint 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>intstack_push(Stack *stack,const void*data){    // Push the  data onto the stack    return list_ins_next(stack, NULL, data);}intstack_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 */voiddestroy(void *data){    printf("in destroy\n");    free(data);    return;}/* main */intmain(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;}

这里写图片描述

0 0
原创粉丝点击