堆栈分为顺序存储 和 链式存储 两种
下面给大家提供一个链式存储的,这里小编是用 C++来描述的堆栈
思路:
堆栈是先进后出的特点,利用这个特点,把表头后作为堆栈口。
设置一个 head表头保持不动,因为 堆栈是只能在一头操作的,所以需要 把 表头后作为堆栈的口,进行出栈入栈操作
#include <iostream>
using namespace std;
typedef
struct Node {
int data;
struct Node * next;
}Node;
class ChainOfStack
{
//int top;
Node head;
void insertAtHead(int data);
void deleteAtHead();
public:
ChainOfStack();
~ChainOfStack();
void push(int data);
void pop();
int top();
void print();
};
ChainOfStack::ChainOfStack()
{
head.data = 0;
head.next = NULL;
}
ChainOfStack::~ChainOfStack()
{
}
void ChainOfStack::push(int data)
{
insertAtHead(data);
}
void ChainOfStack::insertAtHead(int data)
{
Node * tmpNode = new Node;
tmpNode->data = data;
tmpNode->next = head.next;
head.next = tmpNode;
}
void ChainOfStack::pop()
{
deleteAtHead();
}
void ChainOfStack::deleteAtHead()
{
Node * tmpPtr = head.next;
head.next = head.next->next;
delete tmpPtr;
}
int ChainOfStack::top()
{
return head.data;
}
void ChainOfStack::print()
{
Node * p_head = head.next;
while (p_head != NULL) {
cout << p_head->data << " ";
p_head = p_head->next;
}
cout << endl;
}
int main(void)
{
ChainOfStack stack;
cout << "入栈:" << endl;
for (int i = 0; i < 10; i++)
{
stack.push(i);
stack.print();
}
cout << "弹栈:" << endl;
for (int i = 0; i < 10; i++)
{
stack.pop();
stack.print();
}
return 0;
}