forked from mcrwayfun/java-data-structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSequenceStack.java
162 lines (140 loc) · 3.09 KB
/
SequenceStack.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
156
157
158
159
160
161
162
package com.qingtian.source.stack.impl;
import com.qingtian.source.stack.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
/**
* @author mcrwayfun
* @version 1.0
* @description 使用数组来实现栈
* @date Created in 2018/8/2
*/
public class SequenceStack<E> implements Stack<E> {
/**
* 默认长度
*/
private static int DEFAULT_SIZE = 10;
/**
* 当前栈内元素
*/
private int size = 0;
/**
* 数组的长度
*/
private int capacity;
/**
* 保存栈内元素的数组
*/
private Object[] elementData;
public SequenceStack() {
this.capacity = DEFAULT_SIZE;
elementData = new Object[capacity];
}
/**
* 指定长度初始化数组
* @param initSize
*/
public SequenceStack(int initSize) {
this.capacity = initSize;
elementData = new Object[capacity];
}
/**
* 以默认的元素进栈
*
* @param data
*/
public SequenceStack(E data) {
this();
elementData[size++] = data;
}
/**
* 判断栈是否为空
*
* @return
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* 压栈
*
* @param data
* @throws IndexOutOfBoundsException
*/
@Override
public void push(E data) {
// 判断栈是否已经满了
checkIsFull();
elementData[size++] = data;
}
/**
* 出栈,并删除栈顶元素
*
* @return
* @throws IndexOutOfBoundsException
*/
@Override
@SuppressWarnings("unchecked")
public E pop() {
// 判断栈是否为空
checkIsEmpty();
E oldValue = (E) elementData[size - 1];
elementData[--size] = null;
return oldValue;
}
/**
* 查询栈顶元素
*
* @return
* @throws IndexOutOfBoundsException
*/
@Override
@SuppressWarnings("unchecked")
public E peek() {
// 判断栈是否为空
checkIsEmpty();
return (E) elementData[size - 1];
}
/**
* 清空栈
*/
@Override
public void clear() {
Arrays.fill(elementData, null);
size = 0;
}
@Override
public int length() {
return size;
}
/**
* 若栈满了则抛出异常
*/
private void checkIsFull() {
if (size == capacity - 1) {
throw new IndexOutOfBoundsException("栈已经满了");
}
}
/**
* 若栈空则抛出异常
*/
private void checkIsEmpty() {
if (isEmpty()) {
throw new IndexOutOfBoundsException("栈是空的");
}
}
@Override
public String toString() {
if (size == 0) {
return "[]";
} else {
StringBuilder sb = new StringBuilder("[");
for (int i = size - 1; i > -1; i--) {
sb.append(elementData[i].toString() + ", ");
}
int len = sb.length();
return sb.delete(len - 2, len).append("]").toString();
}
}
}