-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
60 lines (53 loc) · 1.14 KB
/
Stack.java
File metadata and controls
60 lines (53 loc) · 1.14 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
package algorithm.stack;
import algorithm.list.Node;
/**
* @ClassName Stack
* @Description 链栈
* @Author changxuan
* @Date 2020/6/23 下午8:05
**/
public class Stack {
Node top;
/**
* 出栈
* @return 栈顶元素
*/
int pop(){
if (top == null){
throw new RuntimeException("this stack is empty");
}
int item = top.data;
top = top.next;
return item;
}
/**
* 入栈
*/
void push(int data){
Node node = new Node(data);
node.next = top;
top = node;
}
int peek(){
if (top == null){
throw new RuntimeException("this stack is empty");
}
return this.top.data;
}
Boolean isEmpty(){
return top == null ? true : false;
}
void sort(){
Stack help = new Stack();
while (!this.isEmpty()){
int cur = this.pop();
while (!help.isEmpty() && help.peek()<cur){
this.push(help.pop());
}
help.push(cur);
}
while (!help.isEmpty()){
this.push(help.pop());
}
}
}