栈 Stack

记录下刚学的栈

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "windows.h"
struct stack_node
{
    int data;
    struct stack_node *next;
};

typedef struct stack_node *PtrToNode;
typedef PtrToNode Stack;
Stack createStack();               //初始化栈
void pushStack(Stack s, int data); //压栈
void popStack(Stack s);            //出栈
void printStack(Stack s);          //打印栈
void getStackTop(Stack s);         //获取栈顶
int main()
{

    Stack S = createStack();
    int i = 0, j = 0;
    for (; i < 10; i++)
    {
        pushStack(S, i);
    }
    for (; j < 10; j++)
    {
        popStack(S);
    }
    // PrintStack(S);
    return 0;
}

Stack createStack()
{
    Stack s;
    s = (Stack)malloc(sizeof(struct stack_node));
    if (s == NULL)
    {
        printf("申请空间失败");
    }
    s->next = NULL;
    return s;
}
//判断是否为空
int isEmtry(Stack s)
{
  return s->next ==NULL?0:1;
  
}
void pushStack(Stack s, int data)
{
    //新的栈顶
    PtrToNode head = (PtrToNode)malloc(sizeof(struct stack_node));
    if (head == NULL)
    {
        printf("push时申请空间失败");
    }

    //push顺序 相当于s->null之间插入head  s->head->null
    head->data = data; //赋值
    head->next = s->next;
    s->next = head;
}

void popStack(Stack s)
{
    PtrToNode head = (PtrToNode)malloc(sizeof(struct stack_node));
    if (head == NULL)
        printf("申请空间失败!\n");

    if (!isEmtry(s))
    {
        printf("栈为空,无法操作");
    }
    else
    {
        head = s->next;       // head_node 为栈顶
        s->next = head->next; // s->next 指向 head_node->next ,即新的栈顶
        printf("出栈结果%d", head->data);
        free(head); // 释放原来栈顶元素所占的内存
    }
}
//打印栈值
void printStack(Stack s)
{
    PtrToNode aim = s->next;

    while (aim)
    {

        printf("%d", aim->data);
        aim = aim->next;
    }
    return;
}

void getStackTop(Stack s)
{
    PtrToNode top = s->next;
    !isEmtry(s) ? printf("栈为空") : printf("栈顶数字为:/d", top->data);

    return;
}

你可能感兴趣的:(栈 Stack)