Implementation of Generics Stack using Linked List in Java [Generics Stack Implementation Using Linked List ]π₯π₯
πDATA STRUCTURE [ STACK IMPLEMENTATION ]
This post shows how to code in JAVA to implementing a Generic Stack using the Linked list.
So, lets start with Stack Basic definition πWhat is the Stack?
Stack: The stack is a very common and non-primitive data structure used in programs. A stack is also called LIFO(Last-In-First-Out).
Stack is a linear list of items in which all insertions and deletion restricted to one end that is Top(Top of the stack).
The following two operations perform on Stack-
- Push (Insertion)
- Pop (Deletion)
Generics:
Java Generics is a set of related methods or a set of similar types. Generics allow types Integer, String, or even user-defined types to be passed as a parameter to classes, methods, or interfaces. Generics are mostly used by classes like HashSet or HashMap.
![]() |
Generics Advantages |
Generics ensure compile-time safety which allows the programmer to catch the invalid types while compiling the code.
Generics Stack Implementation Using Linked List Complete Codeπ
private int length;
{
private E data;
Node next;
public Node(E data){
this.data = data;
}
}
this.head = null;
this.length = 0;
}
return length;
return length == 0;
Node temp = new Node(data);
temp.next = head;
head = temp;
length++;
if(isEmpty())
System.out.println("Stack is Empty!!");
else{
Node temp = head;
System.out.print("Stack Elements : ");
while(temp!= null){
System.out.print(temp.data+" ");
temp = temp.next;
}
}
}
if(isEmpty()){
System.out.println("Stack is Empty!!");
}
return head.data;
if(isEmpty()){
System.out.println("Stack is Empty!!");
}
E result = head.data;
head = head.next;
length--;
return result;
StackImplUsingLinkedList<Number> stack= new StackImplUsingLinkedList<Number>();
//StackImplUsingLinkedList<Object> stack= new StackImplUsingLinkedList<Object>();
// stack.push("p2d");
// stack.push('A');
stack.push(20.00);
stack.push(100);
stack.push(40.12f);
stack.push(50);
stack.show();
System.out.println("\nTop of stack : "+stack.tos());
System.out.println("length : "+stack.length());
stack.pop();
stack.show();
System.out.println("\nTop of stack : "+stack.tos());
System.out.println("length : "+stack.length());
stack.pop();
stack.pop();
stack.pop();
stack.show();
System.out.println("length : "+stack.length());
}
Note: To run this code in your system ,Save this program with StackImplUsingLinkedList.java
0 Comments
if you have any doubts, Please let me know.