阅读背景:

C语言栈的实现(链表实现)

来源:互联网 
#include <stdio.h>
#include <stdlib.h>
//定义节点
typedef struct node
{
    char data;
    struct node * next;
} node;

//定义栈(保留栈顶和栈尾指针)
typedef struct stack
{
    node * top;//用了typedef 给 struct node 取别号为node
    node * buttom;
} stack;

//创立一个空栈
stack * CreateStack()
{
    stack * st = (stack*)malloc(sizeof(stack));
    if(st == NULL)
        return ;//分配空间失败
    st->top = st->buttom;
    return st;
}

//入栈
void Push(stack * st, char data)
{
    node * n = (node *)malloc(sizeof(node));
    n->data = data;
    n->next = st->top;
    st->top = n;
}

//出栈
void Pop(stack * st, char data)
{
    node * n = st->top;
    while(n != st->buttom)//断定是不是是空栈
    {
        if(n->data == data)
        {
            st->top = n->next;
            free(n);//释放空间
            break;
        }
        n = n->next;
    }
}

//打印栈元素
void Display(stack * st)
{
    node * n = (node *)malloc(sizeof(node));
    n = st->top;
    while(n != st->buttom)
    {
        printf("%c  ",n->data);
        n = n->next;
    }
    free(n);
    printf("\n");

}
int main()
{
    int i=5,j=5;
    stack * st;
    st = CreateStack();
    printf("开端进栈:\n");
    while(i--)
    {
        Push(st,"A"+i);
        printf("%c入栈后,栈内元素为: ","A"+i);
        Display(st);
    }
    printf("开端出栈:\n");
    while(j--)
    {

        Pop(st,"E"-j);
        printf("%c出栈后,栈内元素为: ","E"-j);
        Display(st);
    }
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
//定义节点
typ



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: