栈的链式存储的实现与操作

栈的链式存储的实现与操作

 栈的链式存储成为链栈。可以采用一个带头结点的单链表来表示一个链栈,其结点结构和链表相同。栈的插入和删除操作都在头结点后进行。

示例代码

#include 
#include 
typedef struct Node{
    int data;
    struct Node *next;
}StackNode;
StackNode* InitLinkStack(void);
StackNode* PushLinkStack(StackNode *top, int x);
StackNode* PopLinkStack(StackNode *top, int *x);
int main(void)
{
    StackNode *top;
    if((top = InitLinkStack()) == NULL){
        printf("链栈初始化失败!\n");
        exit(1);
    }
    else
        printf("链栈初始化成功!\n");
    int end = 0;
    int ope;
    int n;
    while(!end){
        print_hyphen(15); printf("\n");
        printf("请输入指令来执行操作\n");
        print_hyphen(15); printf("\n");
        printf("1、入栈\n2、出栈\n3、退出\n");
        print_hyphen(15); printf("\n");
        printf("输入要使用的功能的序号: ");
        scanf("%d", &ope);
        switch(ope){
            case 1:
                printf("请输入要入栈的元素: ");
                scanf("%d", &n);
                PushLinkStack(top, n);
                break;

            case 2:
                if(!PopLinkStack(top, &n))
                    printf("栈为空!\n");
                else
                    printf("出栈的元素为: %d\n", n);
                break;

            case 3:
                printf("再见!\n");
                end = 1;
                break;

            default:
                printf("无此序号,请重新输入!\n");
        }
    }
    return 0;
}
StackNode* InitLinkStack(void)
{
    StackNode *top = NULL;
    top = (StackNode*)malloc(sizeof(StackNode));
    top->next = NULL;
    return top;
}
StackNode* PushLinkStack(StackNode *top, int x)
{
    StackNode *p;
    p = (StackNode*)malloc(sizeof(StackNode));
    p->data = x;
    p->next = top->next;
    top->next = p;
    return top;
}
StackNode* PopLinkStack(StackNode *top, int *x)
{
    StackNode *p;
    if(top->next == NULL)
        return NULL;
    else{
        p = top->next;
        *x = p->data;
        top->next = p->next;
        free(p);
        return top;
    }
}
void print_hyphen(int n)
{
    while(n--)
        printf("-");
}

你可能感兴趣的:(数据结构与算法)