Question

How do you implement a stack using a singly linked list in Java? Can you make...

How do you implement a stack using a singly linked list in Java? Can you make it a simple implementation with just push and pop methods.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Stack.java

import static java.lang.System.exit;
//create Stack_using_linked list class
class Stack_Using_LL{
   //Node class
   private class Node{
       int data;
       Node next;
   }
   Node top;
   //constructor
   Stack_Using_LL(){
       this.top = null;
   }
   //Push method.
   //This method add a element at top of the stack
   public void push(int x){
       Node temp = new Node();
       if(temp==null){
           System.out.println("Stack is Overflow");
           return;
       }
       temp.data = x;
       temp.next=top;
       top=temp;
   }
   //Pop method
   //This method will pop the top most element from the stack
   public void pop(){
       if(top==null){
           System.out.println("Stack is Underflow");
           return;
       }
       top = (top).next;
   }
   //Display method
   //This method shows all elements in the stack
   public void display(){
       if(top==null){
           System.out.println("Stack is Underflow");
           exit(1);
       }
       else{
           Node temp =top;
           while(temp!=null){
               System.out.printf("%d\t",temp.data);
               temp=temp.next;
           }
       }
       System.out.println();
   }
}
public class Stack{
   public static void main(String[] args) {
       Stack_Using_LL ob = new Stack_Using_LL();
       ob.push(1);
       ob.push(10);
       ob.push(5);
       ob.push(3);
       ob.display();
      
       ob.pop();
       ob.display();
   }
}

Add a comment
Know the answer?
Add Answer to:
How do you implement a stack using a singly linked list in Java? Can you make...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT