-
Notifications
You must be signed in to change notification settings - Fork 62
/
LinkedStack.java
84 lines (68 loc) · 1.47 KB
/
LinkedStack.java
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
package datastructure.stack;
import java.util.EmptyStackException;
/**
* @author roseduan[roseduan520@gmail.com]
* @time 2019/10/27 15:28
* @description 使用链表实现栈
*/
public class LinkedStack {
private ListNode head;
private int size;
public LinkedStack(int val) {
this.head = new ListNode(val);
this.size = 1;
}
private static class ListNode{
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
/**
* 入栈
*/
public void push(int value) {
ListNode node = new ListNode(value);
size++;
if (head == null) {
head = node;
}
else {
node.next = head;
head = node;
}
}
/**
* 出栈
*/
public int pop(){
if (head == null){
throw new EmptyStackException();
}
ListNode result = head;
head = head.next;
size--;
return result.val;
}
/**
* 获取栈顶元素
*/
public int peek(){
if (head == null){
throw new EmptyStackException();
}
return head.val;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
ListNode p = head;
while (p != null){
sb.append(p.val).append(" ");
p = p.next;
}
return sb.toString();
}
}