顺序栈
栈是一种先入后出的线性数据结构,分为顺序栈和链栈且以顺序栈居多。以下则是顺序栈基于C++的代码实现,供大家参考:
stack.h
#ifndef _stack_H
#define _stack_H
#include <iostream>
#include <malloc.h>
typedef int ElemType;
class Stack
{
ElemType *arr;
int s_top;
size_t capacity;
public:
size_t GetCapacity() const;
size_t size() const;
bool isFull() const;
bool empty() const;
void push(const ElemType x);
void pop();
ElemType top() const;
void clear();
Stack(size_t n);
~Stack();
};
#endif
stack.cpp
#include "stack.h"
#ifdef _stack_H
//获取栈容量
size_t Stack::GetCapacity() const
{
return capacity;
}
//获取栈长度
size_t Stack::size() const
{
return s_top + 1;
}
//判断是否满栈
bool Stack::isFull() const
{
return size() == capacity;
}
//判断栈是否为空
bool Stack::empty() const
{
return s_top == -1;
}
//向栈中压入元素
void Stack::push(const ElemType x)
{
if(isFull())
{
std::cout << "The stack is full." << std::endl;
return;
}
arr[++s_top] = x;
}
//弹出栈顶元素
void Stack::pop()
{
if (empty())
{
std::cout << "The stack is empty." << std::endl;
return;
}
s_top--;
}
//获取栈顶元素
ElemType Stack::top() const
{
if (empty())
{
std::cout << "The queue is empty." << std::endl;
return -1;
}
return arr[s_top];
}
//清空栈中元素
void Stack::clear()
{
s_top = -1;
}
//构造函数:创建容量为n的栈
Stack::Stack(size_t n)
: s_top(-1), capacity(n)
{
arr = (ElemType*)malloc(sizeof(ElemType) * n);
}
//析构函数
Stack::~Stack()
{
free(arr);
arr = nullptr;
}
#endif
循环队列
队列是一种先入先出的线性数据结构,分为顺序队列和链式队列。出于节省空间考虑,我们一般会选用顺序循环队列。以下则是循环队列基于C++的代码实现,供大家参考:
queue.h
#ifndef _queue_H
#define _queue_H
#include <iostream>
#include <malloc.h>
typedef int ElemType;
class Queue
{
ElemType *arr;
size_t font, rear, capacity;
public:
size_t GetCapacity() const;
size_t size() const;
bool isFull() const;
bool empty() const;
void push(const ElemType x);
void pop();
ElemType front() const;
void clear();
Queue(size_t n);
~Queue();
};
#endif
queue.cpp
#include "queue.h"
#ifdef _queue_H
//获取队列容量
size_t Queue::GetCapacity() const
{
return capacity;
}
//获取队列长度
size_t Queue::size() const
{
return (rear + capacity - font) % capacity;
}
//判断是否满队
bool Queue::isFull() const
{
return size() + 1 == capacity;
}
//判断队列是否为空
bool Queue::empty() const
{
return font == rear;
}
//向队列中插入元素
void Queue::push(const ElemType x)
{
if (isFull())
{
std::cout << "The queue is full." << std::endl;
return;
}
arr[rear] = x;
rear = (rear + capacity + 1) % capacity;
}
//弹出队首元素
void Queue::pop()
{
if (empty())
{
std::cout << "The queue is empty." << std::endl;
return;
}
font = (font + capacity + 1) % capacity;
}
//获取队首元素
ElemType Queue::front() const
{
if (empty())
{
std::cout << "The queue is empty." << std::endl;
return -1;
}
return arr[font];
}
//清空队列元素
void Queue::clear()
{
font = rear = 0;
}
//构造函数:创建容量为n的队列
Queue::Queue(size_t n)
: font(0), rear(0), capacity(n + 1)
{
arr = (ElemType*)malloc(sizeof(ElemType) * (n + 1));
}
//析构函数
Queue::~Queue()
{
free(arr);
arr = nullptr;
}
#endif