Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Stack {
- private int size=0;
- private String[] q=new String[0];
- /** Adds a value to the top of the stack.*/
- public void push(String value){
- size++;
- String[] m=new String[size];
- m[0]=value;
- for(int x=1; x<size; x++){
- m[x]=q[x-1];
- }
- q=m;
- }
- /** Removes the topmost string. If the stack is empty, returns null. */
- public String pop() {
- if(size==0)
- return null;
- else
- size--;
- String[] m=new String[size];
- String w = q[size];
- for(int x=0; x<size; x++){
- m[x]=q[x];
- }
- q=m;
- return w;
- }
- /** Returns the topmost string but does not remove it. If the stack is empty, returns null. */
- public String peek() {
- if(isEmpty())
- return null;
- else
- return q[size-1];
- }
- /** Returns true iff the stack is empty */
- public boolean isEmpty() {
- return (size==0);
- }
- /** Returns the number of items in the stack. */
- public int length() {
- return size;
- }
- /** Returns a string representation of the stack. Each string is separated by a newline. Returns an empty string if the stack is empty. */
- public String toString() {
- String s="";
- if(isEmpty())
- return s;
- for(int x=size-1; x>0; x--){
- s+=q[x]+"\n";
- }
- s+=q[0];
- return s;
- }
- }
Add Comment
Please, Sign In to add comment