This is a java homework of stack, please help.!! Question: Imagine a liked imple
ID: 3566085 • Letter: T
Question
This is a java homework of stack, please help.!!
Question: Imagine a liked implementation of the ADT stack that places the top entry of the stack at the end of a chain of line nodes. Describe how you can define the stack operations push, pop. and peek so that they do not traverse the chain.
request? Describe what references you would need in your linked structure. You can include references to particular nodes in the chain or you can include references within each node. Just be clear about what you are including. Then, using those references, describe how you would implement the three methods.
Write a full linked stack implementation as described. Implement a constructor, the three methods you described, isEmpty and clear.
Thankyou for everyone who read it.
Explanation / Answer
/*
The stack will use a double linked list.
And it will have two references,
one to first node, the other to last node.
method push:
create new node
link to last
set last to new node
method pop:
get previous node of last node
set last to previous
set next of last node to null
method peek:
return value of last node
*/
public class TheStack
{
class StackNode
{
StackNode prev;
StackNode next;
Object value;
}
private StackNode first;
private StackNode last;
public TheStack()
{
first = null;
last = null;
}
public void push(Object o)
{
StackNode p = new StackNode();
p.value = o;
p.next = null;
p.prev = last;
if (last == null)
first = p;
else
last.next = p;
last = p;
}
public Object pop()
{
Object result = last.value;
last = last.prev;
if (last == null)
first = null;
else
last.next = null;
return result;
}
public Object peek()
{
return last.value;
}
public boolean isEmpty()
{
return last == null;
}
public void clear()
{
first = null;
last = null;
}
// test main
/*
public static void main(String[] args)
{
TheStack stack = new TheStack();
stack.push("good");
stack.push("bad");
stack.push("zzz");
while (!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
*/
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.