2. Write functions push() and pop() for the Java implementation of an integer st
ID: 3918496 • Letter: 2
Question
2. Write functions push() and pop() for the Java implementation of an integer stack outlined below. The stack is implemented as a singly linked list with a top Node reference. Function push() inserts a new item onto the top of the stack by inserting a new Node at the head of the list. Function pop() deletes the top item, and returns its value.
class Stack{
private class Node{
int item;
Node next;
Node(int item){
this.item = item;
this.next = null;
}
}
private Node top;
private int numItems;
public Stack(){top = null; numItems = 0;}
void push(int x){
// your code goes here
}
int pop(){
// your code goes here
}
Explanation / Answer
class Stack { private class Node { int item; Node next; Node(int item) { this.item = item; this.next = null; } } private Node top; private int numItems; public Stack() { top = null; numItems = 0; } void push(int x) { Node temp = new Node(x); temp.next = top; top = temp; } int pop() { int temp = top.item; top = top.next; return temp; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.