Stacks

A stack is a basic linear data structure in computer programming that behaves like an actual stack or pile, for example, imagine a stack of books.

like the picture you see here not if you want to remove a book from this stack of books the obvious thing to do is to take out the one on top, even if you know the particular book you are looking for you still have to go from top to bottom and the same rule applies if to want to add more books to the stack you place it on top of the existing stack. This is how stacks work and this concept is called last in, first out or LIFO for short this simply means the last node in is the fist node out deletion and insertion is O(1) which is a good thing. Now let’s create a stack class.

 

 

 




public class Stacks {

private static class Node{
private int data;
private Node next;

private Node(int data){
this.data = data;
}
}

private Node top;

//Constructor
public void push(int data){
Node node = new Node(data);
node.next = top;
top = node;
}

// remove the top node
public int pop(){
int data = top.data;
top = top.next;
return data;
}

// see what's on the top of the stack
public int peek(){
return top.data;
}

// check if the stack is empty
public boolean isEmpty(){
return top == null;
}
}

Now let’s call this the Slack class above:

public class Test {

public static void main(String[] args) {

Stacks newStack = new Stacks();

newStack.push(4);
newStack.push(42);
newStack.push(43);
newStack.push(42);
newStack.push(14);
newStack.push(9);

System.out.println(newStack.peek()+ " is on the to of the stack");

System.out.println("after removing the top node");

newStack.pop();

System.out.println("Now the to node is " + newStack.peek());

}

}

And the output will look like this:

9 is on the to of the stack
after removing the top node
Now the to node is 14

 

Leave a Reply

Your email address will not be published.