数据结构——栈和队列

写在前面

使用c++完成,但应该不影响c语言使用者阅读,由于栈的数组模拟比较简单,这不再完成,只完成了链栈的常用操作

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<cctype>
using namespace std;
struct node
{
    char data;
    node *pre,*next;
};
struct Stack
{
    node *head,*last;
    int len;
    Stack()//初始化
    {
        head=new node();
        last=new node();
        head->next=nullptr;
        last=head;
        len=0;
    }
    char do_top()//返回栈顶元素
    {
        return last->data;
    }
    void do_pop()//弹出栈顶元素
    {
        node *p=last->pre;
        free(last);
        last=p;
        last->next=nullptr;
        len--;
    }
    bool isempty()//判断栈是否为空
    {
        if(head==last)
            return true;
        return false;
    }
    void do_push(char x)//压栈
    {
        len++;
        node *newNode = new node();
        newNode->data = x;
        newNode->next = NULL;
        newNode->pre = last;
        last->next = newNode;
        last = newNode;
    }
    int getlen()//返回栈的大小
    {
        return len;
    }
};

队列的实现和栈的实现差不多,只有一些细微差别,但还是感觉数组模拟方便

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<cctype>
using namespace std;
struct node
{
    char data;
    node *pre,*next;
};
struct Queue
{
    node *head,*last;
    int len;
    Queue()//初始化
    {
        head=new node();
        last=new node();
        head->next=nullptr;
        last=head;
        len=0;
    }
    char do_front()//返回队首元素
    {
        return head->data;
    }
    void do_pop()//弹出队首元素
    {
        node *p=head->next;
        free(head);
        head=p;
        len--;
    }
    bool isempty()//判断队列是否为空
    {
        if(head==last)
            return true;
        return false;
    }
    void do_push(char x)//进队
    {
        len++;
        node *newNode = new node();
        newNode->data = x;
        newNode->next = NULL;
        newNode->pre = last;
        last->next = newNode;
        last = newNode;
    }
    int getlen()//返回队列的大小
    {
        return len;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值