forked from mcrwayfun/java-data-structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkStack.java
155 lines (131 loc) · 2.82 KB
/
LinkStack.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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package com.qingtian.source.stack.impl;
import com.qingtian.source.stack.Stack;
/**
* @author mcrwayfun
* @version v1.0
* @date Created in 2018/08/05
* @description 使用链表实现栈
*/
public class LinkStack<E> implements Stack<E> {
private static class Node<E> {
E item;
Node<E> next;
public Node() {
}
public Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
/**
* 当前栈内元素
*/
private int size;
/**
* 栈顶
*/
private Node<E> top;
public LinkStack() {
top = null;
size = 0;
}
/**
* 以默认元素来构建栈
*
* @param data
*/
public LinkStack(E data) {
this();
Node<E> newNode = new Node<>(data, null);
newNode.next = top;
top = newNode;
size++;
}
/**
* 判断栈是否为空
*
* @return
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* 压栈
*
* @param data
*/
@Override
public void push(E data) {
Node<E> newNode = new Node<>(data, null);
newNode.next = top;
top = newNode;
size++;
}
/**
* 出栈,并删除栈顶元素
*
* @return
* @throws IndexOutOfBoundsException
*/
@Override
public E pop() {
// 检查栈是否为空
checkIsEmpty();
Node<E> node = top;
// top指针移动
top = top.next;
// 删除栈顶元素
node.next = null;
size--;
return node.item;
}
/**
* 查询栈顶元素
*
* @return
* @throws IndexOutOfBoundsException
*/
@Override
public E peek() {
// 检查栈是否为空
checkIsEmpty();
return top.item;
}
@Override
public void clear() {
for (Node<E> node = top; node != null; ) {
Node<E> next = node.next;
node.item = null;
node = next;
}
size = 0;
}
@Override
public int length() {
return size;
}
@Override
public String toString() {
//链栈为空链栈时
if (isEmpty()) {
return "[]";
} else {
StringBuilder sb = new StringBuilder("[");
for (Node current = top; current != null
; current = current.next) {
sb.append(current.item.toString() + ", ");
}
int len = sb.length();
return sb.delete(len - 2, len).append("]").toString();
}
}
/**
* 栈为空则抛出异常
*/
private void checkIsEmpty() {
if (isEmpty()) {
throw new IndexOutOfBoundsException("当前栈为空");
}
}
}