Stack.java
package LinearList.Stack;
public abstract class Stack<T> {
public abstract boolean empty();
public abstract T peek();
public abstract T pop();
public abstract void push(T obj);
public abstract int search(T obj);
public abstract int size();
}
StackByArray.java
package LinearList.Stack;
public class StackByArray<T> extends Stack {
private T[] elems;
private int pos; //栈顶指针
private int MaxSize;
private void expansion() {
MaxSize *= 2;
Object tmp = elems;
elems = (T[]) new Object[MaxSize];
System.arraycopy(tmp, 0, elems, 0, pos);
}
public StackByArray() {
pos = -1;
MaxSize = 8;
elems = (T[]) new Object[MaxSize];
}
@Override
public boolean empty() {
return pos < 0;
}
@Override
public T peek() {
try {
return elems[pos];
} catch (Exception e) {
System.out.println("错误,栈为空");
}
return null;
}
@Override
public T pop() {
T obj = null;
try {
obj = elems[pos];
elems[pos] = elems[pos+1];
pos--;
} catch (Exception e) {
System.out.println("错误,栈为空");
}
return obj;
}
@Override
public void push(Object obj) {
if (pos == MaxSize) {
expansion();
}
elems[++pos] = (T) obj;
}
@Override
public int search(Object obj) {
int cnt = 1;
for (T o : elems) {
if (obj.equals(o)) {
return cnt;
}
cnt++;
}
return -1;
}
@Override
public int size() {
return pos+1;
}
}
StackByLinkedList.java
package LinearList.Stack;
public class StackByLinkedList<T> extends Stack {
class Node {
public T val;
Node next;
}
Node head;
public StackByLinkedList() {
head = new Node();
head.next = null;
}
@Override
public boolean empty() {
return head.next == null;
}
@Override
public T peek() {
try {
return head.next.val;
} catch (Exception e) {
System.out.println("错误,栈为空");
}
return null;
}
@Override
public T pop() {
try {
Node tmp = head.next;
head.next = tmp.next;
return tmp.val;
} catch (Exception e) {
System.out.println("错误,栈为空");
}
return null;
}
@Override
public void push(Object obj) {
Node tmp = new Node();
tmp.val = (T) obj;
tmp.next = head.next;
head.next = tmp;
}
@Override
public int search(Object obj) {
int cnt = 1;
Node cur = head.next;
while (cur != null) {
if (obj.equals(cur.val))
return cnt;
cnt++;
cur = cur.next;
}
return -1;
}
@Override
public int size() {
int cnt = 0;
Node cur = head.next;
while (cur != null) {
cur = cur.next;
cnt++;
}
return cnt;
}
}