数据结构-用链表实现栈

用链表的方式实现栈

//栈结构体:
typedef struct stack
{
    int value; //存放数据
    struct stack *next; //指向下一个节点
}STACK_LIST;
//建立空栈,确定head节点
STACK_LIST *CreateNewStack();

//判断栈是否为空
bool IsEmptyStack(STACK_LIST *head);

//入栈
void PushStack(STACK_LIST *head, int elem);

//出栈
void PopStack(STACK_LIST *head);

//获取栈顶元素
STACK_LIST *GetTopElem(STACK_LIST *head);

//获取栈元素个数
int GetTotalNum(STACK_LIST *head);

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
using std::cout;
using std::endl;

typedef struct stack
{
    int value;
    struct stack *next;
}STACK_LIST;
//建立空栈,确定head节点
STACK_LIST *CreateNewStack()
{
    STACK_LIST *head = (STACK_LIST *)malloc(sizeof(STACK_LIST));
    head->next = NULL;
    head->value = -1;
    return head;
}
bool IsEmptyStack(STACK_LIST *head)
{
    if(head->next == NULL)
        return true;
    return false; 
}
//入栈
void PushStack(STACK_LIST *head, int elem)
{
    cout<<"push stack:"<<elem<<endl;
    STACK_LIST *p = (STACK_LIST *)malloc(sizeof(STACK_LIST));
    p->next = head->next;
    head->next = p; 
    p->value = elem;
}
//出栈
void PopStack(STACK_LIST *head)
{
    if(IsEmptyStack(head))
    {
        cout<<"stack is empty!"<<endl;
        return;
    }
    STACK_LIST *p = head->next;
    cout<<"pop stack:"<<p->value<<endl;
    head->next = p->next;
    free(p);
}
//获取栈顶元素
STACK_LIST *GetTopElem(STACK_LIST *head)
{
    if(IsEmptyStack(head))
    {
        cout<<"stack is empty!"<<endl;
        return NULL;
    }  
    return head->next;
}
//获取栈元素个数
int GetTotalNum(STACK_LIST *head)
{
    if(IsEmptyStack(head))
    {
        cout<<"stack is empty!"<<endl;
        return 0;
    }
    int count = 0;
    STACK_LIST *p = head;
    while(p->next != NULL)
    {
        p = p->next;
        count++;
    }
    return count;
}
int main()
{
    STACK_LIST *head = CreateNewStack(); 
    PushStack(head,10); 
    PushStack(head,20); 
    PushStack(head,30); 
    cout<<"total num elem:"<<GetTotalNum(head)<<endl; 
    STACK_LIST *p = GetTopElem(head); 
    cout<<"top elem:"<<p->value<<endl;
    PopStack(head);
    PopStack(head);
    PopStack(head);
    cout<<"total num elem:"<<GetTotalNum(head)<<endl; 
    return 0;    
}

打印结果:

push stack:10
push stack:20
push stack:30
total num elem:3
top elem:30
pop stack:30
pop stack:20
pop stack:10
stack is empty!
total num elem:0

 参考:

https://www.cnblogs.com/zhang01010/p/7749342.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值