How to Implement Java Data Structures
Q: Implement a Java-based data structure, such as a stack, queue, or binary tree, including features such as traversal, searching, and sorting.
- Java
- Senior level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
Here's an example of implementing a stack data structure in Java:
public class Stack<T> { private Node<T> top; private static class Node<T> { private T data; private Node<T> next; public Node(T data) { this.data = data; } } public void push(T data) { Node<T> newNode = new Node<>(data); newNode.next = top; top = newNode; } public T pop() { if (top == null) { throw new NoSuchElementException(); } T data = top.data; top = top.next; return data; } public T peek() { if (top == null) { throw new NoSuchElementException(); } return top.data; } public boolean isEmpty() { return top == null; } public int size() { int size = 0; Node<T> currentNode = top; while (currentNode != null) { size++; currentNode = currentNode.next; } return size; } }
This implementation of a stack data structure in Java includes the basic operations of push, pop, peek, isEmpty, and size. It uses a generic type parameter to allow the stack to hold any type of data. The stack is implemented using a linked list with a top reference to the most recently added element. The push method adds a new node to the top of the stack, the pop method removes the top node and returns its data, and the peek method returns the data of the top node without removing it. The isEmpty method checks if the stack is empty and the size method returns the number of nodes in the stack.


