编程实现栈的入栈/出栈操作

完整代码如下,其实队栈都只是链表的一种变化而已

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

typedef struct student * PNode;
typedef struct stacklink * PStack;

typedef struct student
{
    int data;
    PNode next;
}Node;

typedef struct stacklink
{
    PNode zhandi;
    PNode top;
}Stack;

PStack push(PStack stack,int num)
{
    PNode p=(PNode)malloc(sizeof(Node));
    PNode temp;
    PStack q=stack;
    p->data=num;
    if(stack==NULL)
    {
        q=(PStack)malloc(sizeof(Stack));
        q->zhandi=p;
        q->top=p;
        q->zhandi->next=NULL;
        q->top->next=NULL;
        return q;
    }
    temp=q->top;
    q->top=p;
    q->top->next=temp;
    return q;
}

void print(PStack stack)
{
    if(stack==NULL)
    {
        printf("栈为空
");
        return;
    }
    PStack q=stack;
    PNode p=q->top;
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("
");
}

PStack pop(PStack stack)
{
    if(stack==NULL)
    {
        printf("栈为空
");
        return NULL;
    }
    PStack q=stack;
    PNode temp=q->top;
    if(q->top->next==NULL)
    {
        printf("栈只有一个结点,删除完毕
");
        return NULL;
    }
    q->top=q->top->next;
        return q;
}

int main(void)
{
    int flag;
    int num;
    PStack stack=NULL;
    while(1)
        {
               printf("选择入栈或者出栈:1为入栈,2为出栈,0为退出
");
            scanf("%d",&flag);
            if(flag==1)
             {
                 printf("请选择要入栈的值:
");
                scanf("%d",&num);
                stack=push(stack,num);
                    printf("打印入栈后的栈:
");
                print(stack);
            }
            else if(flag==2)
            {
                    stack=pop(stack);
                    printf("打印出栈后的队列:
");
                    print(stack);
            }
    }
    q->top=q->top->next;
        return q;
}

int main(void)
{
    int flag;
    int num;
    PStack stack=NULL;
    while(1)
        {
               printf("选择入栈或者出栈:1为入栈,2为出栈,0为退出
");
            scanf("%d",&flag);
            if(flag==1)
             {
                 printf("请选择要入栈的值:
");
                scanf("%d",&num);
                stack=push(stack,num);
                    printf("打印入栈后的栈:
");
                print(stack);
            }
            else if(flag==2)
            {
                    stack=pop(stack);
                    printf("打印出栈后的队列:
");
                    print(stack);
            }
            else
                    break;
    }    
    return 0;
}

 程序猿必读

原文地址:https://www.cnblogs.com/longzhongren/p/4418323.html