0% found this document useful (0 votes)
23 views

Import Javaio

This document defines a Node class to represent nodes in a linked list, with data and next pointer fields. It also defines a Stack class using the linked list to implement a stack data structure with push, pop and display methods. The main method prompts the user for input to push or pop elements from the stack and display its contents.

Uploaded by

MAHESHWARAN.R
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Import Javaio

This document defines a Node class to represent nodes in a linked list, with data and next pointer fields. It also defines a Stack class using the linked list to implement a stack data structure with push, pop and display methods. The main method prompts the user for input to push or pop elements from the stack and display its contents.

Uploaded by

MAHESHWARAN.R
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.io.

*;
class Node
{
public int data;
public Node next;
public Node(int x)
{
data=x;
}
public void display()
{
System.out.println(data+" ");
}
}
class Stack
{
public Node first;
public Stack()
{
first=null;
}
public boolean isEmpty()
{
return(first==null);
}
public void push(int value)
{
Node newnode=new Node(value);
newnode.next=first;
first=newnode;
}
public int pop()
{
if(isEmpty())
{
System.out.println("\n Stack is Empty...");
return 0;
}
else
{
int r1=first.data;
first=first.next;
return r1;
}
}
public void display()
{
Node current=first;
while(current!=null)
{
System.out.print(" "+current.data);
current=current.next;
}
System.out.println("");
}
}
class StackList
{
public static void main(String args[]) throws IOException
{
Stack S=new Stack();
int ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("\nMENU");
System.out.println("----------");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the number of elements to
push: ");
int n1=Integer.parseInt(br.readLine());
System.out.println("\nEnter the elements: ");
for(int i=0; i<n1; i++)
{
S.push(Integer.parseInt(br.readLine()));
}
break;
case 2:
System.out.println("\nEnter the number of elements to
pop: ");
int n2=Integer.parseInt(br.readLine());
for(int i=0; i<n2; i++)
{
System.out.println(S.pop()+" is popped from
stack... ");
}
break;
case 3:
System.out.println("\nStack elements are:");
S.display();
break;
default:
break;
}
}
while(ch!=4);
}
}

You might also like