数据结构——栈、队列

一、栈

定义:栈是一个先入后出First In Last Out)的数据结构

四个功能,插入,删除,判空,输出栈顶。

int stack[N],tt = 0;

void push(int a) //向栈顶加入元素
{
    stack[tt++] = a;
}

void pop()		//删除栈顶元素
{
    tt--;
}

bool empty()	//判断栈是否为空
{
    if( tt)
        return 1;
    return 0;
}

int top()		//输出栈顶元素
{
    return stack[tt-1];
}

二、队列

定义:队列是一个先入先出First In First Out)的数据结构.

同样四个功能:插入、删除、判空、输出队头

int queue[N], hh = 0, tt = -1;

void push( int a)	//向队列尾插入元素
{
    queue[ ++tt] = a;
}

void pop()			//删除队头元素
{
    hh++;
}

bool empty()		//判断队列是否为空
{
    if( hh > tt)
        return 0;
    return 1;
}

int top()			//输出队头元素
{
    return queue[hh];
}

为什么用数组模拟?因为快啊,数组模拟跑起来比STL快。

原文地址:https://www.cnblogs.com/trirabbits/p/11747664.html