一、入栈图
二、代码实现
package com. xianxing. stack;
public class MyStack {
int [ ] elements;
public MyStack ( ) {
elements = new int [ 0 ] ;
}
public void push ( int element) {
int newArr[ ] = new int [ elements. length + 1 ] ;
for ( int i = 0 ; i < elements. length; i++ ) {
newArr[ i] = elements[ i] ;
}
newArr[ elements. length] = element;
elements = newArr;
}
public String show ( ) {
String stackString = "" ;
for ( int i = elements. length - 1 ; i >= 0 ; i-- ) {
stackString += elements[ i] + " " ;
}
return stackString;
}
public int pop ( ) {
if ( elements. length == 0 ) {
throw new RuntimeException ( "stack is empty!" ) ;
}
int element = elements[ elements. length - 1 ] ;
int newArr[ ] = new int [ elements. length - 1 ] ;
for ( int i = 0 ; i < elements. length - 1 ; i++ ) {
newArr[ i] = elements[ i] ;
}
elements = newArr;
return element;
}
public int peek ( ) {
if ( elements. length == 0 ) {
throw new RuntimeException ( "stack is empty!" ) ;
}
return elements[ elements. length - 1 ] ;
}
public boolean isEmpty ( ) {
return elements. length == 0 ;
}
}
package com. xianxing. stack;
public class TestMyStack {
public static void main ( String[ ] args) {
MyStack ms = new MyStack ( ) ;
ms. push ( 9 ) ;
ms. push ( 8 ) ;
ms. push ( 7 ) ;
ms. push ( 6 ) ;
System. out. println ( ms. show ( ) ) ;
System. out. println ( ms. pop ( ) ) ;
System. out. println ( ms. pop ( ) ) ;
System. out. println ( ms. peek ( ) ) ;
ms. pop ( ) ;
System. out. println ( ms. peek ( ) ) ;
System. out. println ( ms. isEmpty ( ) ) ;
ms. pop ( ) ;
System. out. println ( ms. isEmpty ( ) ) ;
}
}