用单链表来实现栈,插入和删除的部分很有意思。
写完这个感觉突然理解了书上说的适配器的观点,类就是这样,不管你底层实现是什么,表现成什么就好了,是一个黑盒。
头文件Mystack.h
#ifndef MYSATCK_H
#define MYSTACK_H
struct Node
{
int data;
Node *next;
};
class LUStack
{
public:
LUStack();
~LUStack();
void Push(int data);
void Pop();
int Top();
private:
void Insert(Node* t, int data);
void Erase(Node *t);
Node *head;
};
#endif
定义Mystack.cpp
#include "Mystack.h"
LUStack::LUStack()
{
head = new Node;
head->next = nullptr;
}
LUStack::~LUStack()
{
delete head;
head = nullptr;
}
void LUStack::Insert(Node* t, int data)
{
Node *p = new Node;
p->data = data;
p->next = t->next;
t->next = p;
}
void LUStack::Erase(Node *t)
{
Node *p = new Node;
p = t->next->next;
delete t->next;
t->next = p;
}
void LUStack::Push(int data)
{
Insert(head, data);
}
void LUStack::Pop()
{
Erase(head);
}
int LUStack::Top()
{
return head->next->data;
}
测试数据
#include "Mystack.h"
#include<iostream>
int main()
{
LUStack test;
test.Push(4);
test.Push(3);
test.Push(7);
test.Push(8);
std::cout << test.Top() << std::endl;
test.Pop();
std::cout << test.Top()<< std::endl;
test.Pop();
std::cout << test.Top()<< std::endl;
test.Pop();
std::cout << test.Top()<< std::endl;
test.Pop();
system("pause");
return 0;
}