码迷,mamicode.com
首页 > 其他好文 > 详细

单链表实现栈

时间:2015-10-15 18:33:46      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>

typedef char stack_element_t;

typedef struct stack_node_s
{
    stack_element_t element;
    struct stack_node_s *restp;
}stack_node_t;

/*Stack top pointer*/
typedef struct
{
    stack_node_t *topp;
}stack_t;

void push(stack_t *sp, stack_element_t c)
{
    stack_node_t *newp;
    
    /*Creates and defines new node*/
    newp = (stack_node_t*)malloc(sizeof(stack_node_t));
    newp->element = c;
    newp->restp = sp->topp;
    
    /*Renew stack top pointer*/
    sp->topp = newp;
}

stack_element_t pop(stack_t *sp)
{
    stack_node_t *to_freep;
    stack_element_t ans;
    
    to_freep = sp->topp;
    ans = to_freep->element;
    sp->topp = to_freep->restp;
    free(to_freep);
    
    return ans;
}

int main(void)
{
    stack_t s = {0};
    
    push(&s, 2);
    push(&s, +);
    push(&s, C);
    push(&s, /);
    
    printf("\nEmptying stack: \n");
    while(s.topp != NULL)
        printf("%c\n", pop(&s));
        
    return 0;    
}

单链表实现栈

标签:

原文地址:http://www.cnblogs.com/xbon/p/4883063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!