snippetjavaMinor
Implement stack using a linked list
Viewed 0 times
stackimplementusinglistlinked
Problem
I am trying to implement Stack using a linked list. Looking for code-review, best practices and optimizations.
public class StackUsingLinkedList {
private Node top;
int size;
public StackUsingLinkedList() {
}
private static class Node {
Node next;
T item;
public Node (T item, Node next) {
this.item = item;
this.next = next;
}
}
/**
* Push the item into the stack
*
* @param item the item to be pushed.
*/
public void push(T item) {
final Node node = new Node(item, top);
top = node;
size++;
}
/**
* Pops the item from the stack
*
* @return the popped item
* @throws EmptyStackException if attempt is made to access/pop out of an empty stack.
*/
public T pop() {
if (top == null) {
throw new EmptyStackException();
}
T item = top.item;
top = top.next;
return item;
}
/**
* Returns the item at top of the stack.
*
* @return the item at top of stack.
* @throws EmptyStackException if attempt is made to access empty stack
*/
public T peek () {
if (top == null) {
throw new EmptyStackException();
}
return top.item;
}
public int size() {
return size;
}
public boolean isEmpty() {
return top == null;
}
public static void main(String[] args) {
StackUsingLinkedList s = new StackUsingLinkedList();
s.push(10);
s.push(20);
// expected 20, 10.
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}Solution
This is generally good code, with standards-conforming names and style.
It appears that
Additionally, even in the inner private Node class, I would recommend declaring the
Otherwise, this is good code.
It appears that
size is an afterthought variable. It is not scoped as being 'private', and it is not decreased in the pop() method, so it is buggy in two ways.Additionally, even in the inner private Node class, I would recommend declaring the
item and next as private, and also adding getters/setters for them.Otherwise, this is good code.
Context
StackExchange Code Review Q#54915, answer score: 2
Revisions (0)
No revisions yet.