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

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; } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote