数据布局——基于list的stack&盘算后缀表达式(代码)

2022-11-17 09:41:10 作者:春慵
导读:数据结构——基于list的stack&计算后缀表达式(代码),//注:中午发现此应用仅局限于个位数字的运算#include "pch.h"#include #include using namespace std;templateclass Stack//基...

//注:中午发觉此应用仅范围于个位数字的运算

#include "pch.h"

#include

#include

using namespace std;

template

class Stack//基于链表的栈

{

private:

struct Node

{

T data;

Node *next;

};

Node *head;//链表的不动端

Node *p;//栈最顶真个谁人节点

int length;//栈的数据个数

public:

Stack()//初始化

{

head = NULL;

length = 0;

}

void push(T n)//入栈

{

Node *q = new Node;

q->data = n;

if (head == NULL)//确定head作为链表的不动端

{

q->next = head;

head = q;

p = q;

}

else//从链表动端延伸链表

{

q->next = p;

p = q;

}

length++;

}

T pop()//出栈而且将出栈的元素返回

{

if (length <= 0)

{

return 0;

}

Node *q = p;

int value;

value = p->data;

p = p->next;

delete q;//析构节点

length--;

return value;

}

int size()//返回元素个数

{

return length;

}

T top()//返回栈顶元素

{

return p->data;

}

bool isEmpty()//推断栈是不是空的

{

if (length == 0)

{

return true;

}

else

{

return false;

}

}

void clear()//清空栈中的全部元素

{

if (head == NULL)

{

return ;

}

while (length > 0)

{

Node *ptr = p;

p = p->next;

delete ptr;

length--;

}

}

};

int main()

{

//----测试字符货仓----------------------

cout << "1.字符堆入测试:" << endl;

Stack s;

//-----将abcdefghij按次序堆入栈内-------

for (int i = 0; i < 10; i++)

{

s.push('a' + i);

}

cout << "测试栈顶元素:" << endl;

cout << s.top() << endl;

cout << "栈的元素个数:" << s.size() << endl;

//-----将栈内的全部数据输出-------------

cout << "将栈内的全部数据输出" << endl;

while (!s.isEmpty())

{

cout << s.pop() << endl;

}

//----再次将abcdefghij按次序堆入栈内-----

for (int i = 0; i < 10; i++)

{

s.push('a' + i);

}

//----清空栈------------------------------

cout << endl;

cout << "清栈测试:" << endl;

s.clear();

//----测试该栈是否被全部清空,否则将栈元素全部输出---

if (s.isEmpty())

{

cout << "该栈已经被全部清空" << endl;

}

else

{

while (!s.isEmpty())

{

cout << s.pop() << endl;

}

}

//----测试数字货仓---------------------

cout <<"----------------------------------------"<

cout << "2.数字堆入测试:" << endl;

Stack c;

//-----将0123456789按次序堆入栈内-------

for (int i = 0; i < 10; i++)

{

c.push(i);

}

//-----将栈内的外五个元素输出-------------

for(int i = 0;i < 5;i++)

{

cout << c.pop() << endl;

}

//----中途堆入元素11--------

cout << endl;

cout << "中途插入测试:" << endl;

c.push(11);

//-----将栈内的全部数据输出-------------

while (!c.isEmpty())

{

cout << c.pop() << endl;

}

cout << "------------测试结束--------------------------"<

Stackx;

char a;

while (cin >> a)

{

if (a >= '0'&&a <= '9')

{

int b = a - '0';

x.push(b);

}

if (a == '+')

{

int b = x.pop() + x.pop();

x.push(b);

}

if (a == '-')

{

int b = (-x.pop()) + x.pop();

x.push(b);

}

if (a == '*')

{

int b = x.pop() * x.pop();

x.push(b);

}

if (a == '/')

{

int b = x.pop() / x.pop();

x.push(b);

}

}

if (x.size() == 1)

{

cout << "您的计算结果为:"<

}

else

{

cout << "您的输入有误!!!" << endl;

}

return 0;

}

精彩图集