-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
110 lines (99 loc) · 1.33 KB
/
Copy pathstack.cpp
File metadata and controls
110 lines (99 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
*利用链表实现一个简单的栈
*2019-2-25
*/
#include<iostream>
using namespace std;
//构造一个链表节点的结构体
struct Node {
int val;
Node *next;
};
//定义栈的类
class Stack {
public:
void init();
void push(int e);
void pop();
int top();
bool IsEmpty();
int Length();
private:
int length=0;
Node *head;
};
//初始化栈
void Stack::init()
{
head= new Node();
length = 0;
}
//push操作
void Stack::push(int e)
{
Node *p = new Node();
p->val = e;
p->next = nullptr;
if (!head->next)
{
head->next = p;
++length;
}
else
{
p->next = head->next;
head->next = p;
++length;
}
}
//pop操作
void Stack::pop()
{
if (!head->next)
cout << "栈为空!" << endl;
else
{
Node *q = head->next;
head->next = q->next;
delete q;
--length;
}
}
//获取栈顶元素值
int Stack::top()
{
if (!head->next)
return -1;
else
{
return head->next->val;
}
}
//判断栈是否为空
bool Stack::IsEmpty()
{
if (!head->next)
return true;
else
return false;
}
//获取栈的长度
int Stack::Length()
{
return length;
}
int main()
{
Stack s;
s.init();
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.pop();
cout << "栈顶元素为: " << endl;
cout << s.top() << endl;
cout << "栈长度为: " << endl;
cout << s.Length() << endl;
return 0;
}