《算法导论》在介绍了一些排序算法以及关于它们运行的时间分析后,开始介绍一些简单的数据结构,栈,队列,表,有根树···这些是实现高级数据结构以及更多算法设计的基础知识,有一种排序算法是桶排序,可以利用链表的结构在线性时间内完成排序。
栈和队列是经常放在一块比较的两种结构,栈的特性是先进后出(FILO),而队列的特性是先进先出(FIFO)。在现实生活中可以找到很多有这两种特性的例子,笔者在此不作赘述。实现栈和队列可以用数组或者指针的方式,这里先介绍用数组的方式实现。
对于栈,由其FILO的特性,需要一个top标志,用来表示栈的最上面的元素,针对栈的操作也只有入栈push和出栈pop,另外栈的空间是有限的,需要对栈的状态进行判断。
用C++编程实现简单的数组栈操作代码如下:
#include
int top = -1;
const int MAX = 10;
bool stack_is_empty();
bool stack_is_full();
void push(int S[]);
void pop(int S[]);
int main(void)
{
int S[MAX];
int choose = 0;
std::cout << "Please enter your choose<1 to push; 2 to pop; 3 to quit>: ";
while (std::cin >> choose && choose != 3)
{
if (choose == 1)
push(S);
else if (choose == 2)
pop(S);
std::cout << "Please enter your choose<1 to push; 2 to pop; 3 to quit>: ";
}
return 0;
}
bool stack_is_empty()
{
if (top == -1)
return true;
return false;
}
bool stack_is_full()
{
if (top == MAX -1)
return true;
return false;
}
void push(int S[])
{
if (stack_is_full())
{
std::cout << "Stack is empty!\n";
}
else
{
std::cout << "Please input the element:";
std::cin >> S[++top];
}
}
void pop(int S[])
{
if (stack_is_empty())
{
std::cout << "Stack is empty!\n";
}
else
{
std::cout << S[top--] << std::endl;
}
}
对于队列,则需要一个head标志表示队列头,tail标志表示队列尾。最基本的操作也是有两个,插入队列和从队列中移除,队列的空间也是有限的,其状态同样需要进行判断。
用C++编程实现简单的数组队列代码如下:
#include
int head = 0;
int tail = 0;
const int length = 10;
bool queue_is_empty();
bool queue_is_full();
void enqueue(int Q[]);
void dequeue(int Q[]);
int main(void)
{
int Q[length];
std::cout << "Please enter the choose<1 to add; 2 to delete; 3 to quit>: ";
int choose = 0;
while (std::cin >> choose && choose != 3)
{
if (choose == 1)
enqueue(Q);
else if (choose == 2)
dequeue(Q);
std::cout << "Please enter the choose<1 to add; 2 to delete; 3 to quit>: ";
}
return 0;
}
bool queue_is_empty()
{
if (head == tail)
return true;
return false;
}
bool queue_is_full()
{
if (head == (tail + 1) % length)
return true;
return false;
}
void enqueue(int Q[])
{
if (queue_is_full())
{
std::cout << "Queue is full!\n";
}
else
{
std::cout << "Please enter the element: ";
std::cin >> Q[tail];
tail++;
if (tail == length)
tail -= length;
}
}
void dequeue(int Q[])
{
if (queue_is_empty())
{
std::cout << "Queue is empty!\n";
}
else
{
std::cout << Q[head] << " has deleted!\n";
head++;
if (head == length)
head -= length;
}
}
可以看到,用数组的方式实现,有很多的缺陷,但是如果对于数据量不是很多的时候,这种实现的方式比较容易也是可取的。随着学习的深入,笔者将在这本经典书籍的引领下开始窥探算法的冰山一角。