Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

convert the following stack into using a linked list instead of an array: packag

ID: 3564863 • Letter: C

Question

convert the following stack into using a linked list instead of an array:

package MyStackQueue;

public class Stack{
    private Object object[];
    private int i;
    private int j;
    public Stack(){
        i = -1;
        j = 100;
        object = new Object[j];
    }
    public Object pop(){
        Object object2 = object[i];
        object[i--] = null;
       return object2;
    }
    public void push(Object object2){
        object[++i] = object2;
    }
    public Object top(){
        return object[i];
   }
    public boolean isEmpty(){
        return i < 0;
    }
}

Explanation / Answer

// indented code looks and feels better http://pastebin.com/KkWQnupe

// Each operation of complexity O(1)

import java.util.Objects;

public class Stack {

private class Node {
Object data;
Node next;

public Node(Object data) {
this.data = data;
this.next = null;
}
}

private Node head;

// Elements are added and removed from front of list
// i.e. front works as top

public void push(Object data) {
if (isEmpty()) {
head = new Node(data);
} else {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
}

public Object pop() {
Object result = head;
if (!isEmpty()) {
head = head.next;
}
return result;
}

public Object top() {
return head;
}
  
public boolean isEmpty() {
return head == null;
}

}