棧 Stack

記錄下剛學(xué)的棧

#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("申請(qǐng)空間失敗");
    }
    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時(shí)申請(qǐng)空間失敗");
    }

    //push順序 相當(dāng)于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("申請(qǐng)空間失敗!\n");

    if (!isEmtry(s))
    {
        printf("棧為空,無法操作");
    }
    else
    {
        head = s->next;       // head_node 為棧頂
        s->next = head->next; // s->next 指向 head_node->next ,即新的棧頂
        printf("出棧結(jié)果%d", head->data);
        free(head); // 釋放原來?xiàng)m斣厮嫉膬?nèi)存
    }
}
//打印棧值
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("棧頂數(shù)字為:/d", top->data);

    return;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容