public class Stack {
@Test
public void test() {
ArrayStack arrayStack = new ArrayStack();
System.out.println("------------------------------");
arrayStack.push(11);
arrayStack.push(1);
arrayStack.show();
arrayStack.push(2);
arrayStack.push(3);
System.out.println("------------------------------");
System.out.println("------------------------------" + arrayStack.pop());
arrayStack.push(4);
arrayStack.push(5);
arrayStack.push(6);
arrayStack.push(7);
arrayStack.push(8);
arrayStack.show();
arrayStack.push(9);
arrayStack.push(10);
System.out.println("------------------------------" + arrayStack.push(100));
System.out.println("------------------------------" + arrayStack.pop());
arrayStack.show();
LinkedStack linkedStack = new LinkedStack();
linkedStack.push(11);
linkedStack.push(22);
linkedStack.push(33);
linkedStack.push(44);
System.out.println("==============="+linkedStack.pop());
linkedStack.push(55);
linkedStack.push(66);
linkedStack.push(77);
linkedStack.push(88);
linkedStack.show();
}
class ArrayStack {
int[] array = new int[3];
double factor = 0.75;
int index = 0;
public boolean push(int value) {
if (index > 0 && index >= array.length * factor) {
int[] arrayNew = new int[array.length * 2];
for (int i = 0; i < array.length; i++) {
arrayNew[i] = array[i];
}
array = arrayNew;
}
array[index] = value;
index++;
return true;
}
public int pop() {
int value = 0;
if (index > 0) {
value = array[--index];
}
return value;
}
public void show() {
for (int i = 0; i < array.length; i++) {
System.out.println("------------(" + array[i] + ")");
}
}
}
class LinkedStack {
Node head = null;
public void push(int value){
Node temp = new Node(value);
if(head == null){
head = temp;
return;
}
Node current = head;
temp.next = current;
head = temp;
}
public int pop(){
Node current = head;
if(current==null){
return -1;
}
int value = current.value;
head = head.next;
return value;
}
public void show(){
Node current = head;
while (current!=null){
System.out.println("===============["+current.value+"]");
current = current.next;
}
}
}
}