目录
1.问题描述
栈是一种先进后出,后进先出的数据结构,访问栈的数据只能通过出栈的方式或者通过获取栈顶元素的方式来访问。既然我们不能像链表那样一个一个访问结构中的元素,但是我们可以通过链表这种结构来实现栈。
2.解题思路
我们用list_stack表示栈,可以在类的成员里面添加成员变量head,用来表示链表的头结点,由于链表是后进先出的,还需要一个变量记录头结点到尾结点的距离,用于记录出栈的位置。
3.代码实现
list_stack的头文件,list_stack.h,定义了我们需要用到的成员变量和成员函数。
#pragma once
#include<iostream>
#include<exception>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
};
class list_stack
{
public:
list_stack();
~list_stack();
void push(int );//入栈
int pop();//出栈
int top();//取出栈顶元素
bool empty();//判断栈是否为空
private:
ListNode* head=nullptr;//用于存储数据
int count = 0;//用于维护出栈入栈的位置
};
list_stack.cpp,我们实现了各种函数。
#include "list_stack.h"
list_stack::list_stack()
{
head = new ListNode();
}
list_stack::~list_stack()
{
}
void list_stack::push(int val)//入栈
{
try
{
ListNode* tmp = head;
for (int move = 0; move < count; move++)
{
tmp = tmp->next;
}
ListNode* newnode = new ListNode;
tmp->next = newnode;
newnode->val = val;
newnode->next = nullptr;
++count;
}
catch(const std::exception&e)
{
cout << e.what() << endl;
}
}
int list_stack::pop()//出栈
{
try
{
int move = count;
ListNode* tmp = head;
for (int move = 0; move < count-1; move++)
{
tmp = tmp->next;
}
ListNode* del = tmp->next;
tmp->next = nullptr;
int res = del->val;
delete del;
--count;
return res;
}
catch (const std::exception& e)
{
cout << e.what() << endl;
}
}
int list_stack::top()//取出栈顶元素
{
try
{
if (count == 0) throw exception("栈为空");
ListNode* tmp = head;
for (int move = 0; move < count; move++)
{
tmp = tmp->next;
}
return tmp->val;
}
catch (const std::exception& e)
{
cout << e.what() << endl;
}
}
bool list_stack::empty()//判断栈是否为空
{
return head->next ? false : true;
}