栈的基本操作:
入栈,出栈,和返回栈顶元素
入栈///
我们把链表的尾部作为栈的出入口
所以需要用一个尾指针 tail 来指向链表的末尾,然后在链表的最后添加节点,就可以实现入栈的操作了///
typedef struct node {
int data;
struct node* next;
struct node* before;
}NODE;
NODE* head = nullptr;
NODE* tail = nullptr;
void _push_(int data) //入栈操作
{
NODE* _temp = new NODE();
if (_temp == NULL)
{
cout << "no enough memory...\n";
system("pause");
exit(0);
}
_temp->next = NULL;
_temp->data = data;
if (head == NULL)
{
head = _temp;
tail = head;
head->before = NULL;
return;
}
tail->next = _temp;
_temp->before = tail;
//更新尾节点
tail = _temp;
return;
}
出栈///
在这里,我设置了一个双向的链表来提高出栈的效率
所以出栈只需要删除链表尾部的节点就好了
void _pop_() //出栈
{
NODE* _temp = tail;
tail = tail->before;
tail->next = NULL;
delete _temp;
return;
}
返回栈顶元素///
也就是返回链表最后一个节点的数据了///
inline int _top_() { return tail->data; }
总体代码实现
#include <iostream>
using namespace std;
typedef struct node {
int data;
struct node* next;
struct node* before;
}NODE;
NODE* head = nullptr;
NODE* tail = nullptr;
void _push_(int data)
{
NODE* _temp = new NODE();
if (_temp == NULL)
{
cout << "no enough memory...\n";
system("pause");
exit(0);
}
_temp->next = NULL;
_temp->data = data;
if (head == NULL)
{
head = _temp;
tail = head;
head->before = NULL;
return;
}
tail->next = _temp;
_temp->before = tail;
//更新尾节点
tail = _temp;
return;
}
void _pop_()
{
NODE* _temp = tail;
tail = tail->before;
tail->next = NULL;
delete _temp;
return;
}
inline int _top_() { return tail->data; }
int main()
{
//入栈
for (int i = 0; i <= 10; ++i)
_push_(i);
//出栈
_pop_();
//返回栈顶元素
cout << _top_() << '\n';
system("pause");
return 0;
}
再见 = = ///