链栈

#include<stdio.h>
#include<stdlib.h>
typedef int type;
typedef struct Node
{
    type info;
    struct Node*next;
}node;
//返回一个栈的头指针
node*init()
{
    node*head=(node*)malloc(sizeof(node));
    head->next=NULL;
    return head;
}
//将值为x的节点压栈
void push(node*head,type x)
{
    node*p=(node*)malloc(sizeof(node));
    p->info=x;
    p->next=head->next;
    head->next=p;
}
//打印栈
void display(node*head)
{
    node*p=head->next;
    while(p){
        printf("%5d",p->info);
        p=p->next;
    }
    printf("\n");
}
//销毁栈
void destory(node*head)
{
    node*p=head,*q;
    while(p){
        q=p->next;
        free(p);
        p=q;
    }
}
//判断栈是否为空
int empty(node*head)
{
    return head?0:1;
}
//出栈
void pop(node*head)
{
    if(!empty(head)){
            node*p=head->next;
            head->next=p->next;
            free(p);
        }
    else printf("error\n");
}
//返回栈顶元素
type top(node*head)
{
    if(!empty(head))
        return head->next->info;
    else {
        printf("error\n");
        return -1;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-01-30 17:38  Thereisnospon  阅读(114)  评论(0)    收藏  举报