Question

Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the...

Instructions:

SLLStack (12 pts)

● Using the two properties below, implement the stack

interface using the SLLNode class from Lab 2:

top_node → SLLNode object or None

size → int, keep track of stack size

● Implement the push( ), pop( ), top( ) methods

● Use SLLNode methods:

get_item( ), set_item( ), get_next( ), set_next( )

● (5 pts) In push(item):

○ Create new SLLNode with item

○ Add new node before top node

○ Update top_node and size properties

● (5 pts) In pop( ):

○ If empty, raise Exception('Empty stack: cannot pop')

○ Remove top node and return its item

○ Remove any links from old top node

○ Update top_node and size properties

● (2 pts) In top( ):

○ If empty, raise Exception('Empty stack: no top')

○ Return top node’s item

Code:

class SLLStack:
   def __init__(self):
       # NOTE: DO NOT EDIT THIS CODE
       # constructor: set properties top_node, size
       self.top_node = None
       self.size = 0

   def __repr__(self):
       # NOTE: DO NOT EDIT THIS CODE
       # string representation of SLLStack object
       display = []
       node = self.top_node
       while node != None:
           display.append(str(node.get_item()))
           node = node.get_next()
       display = ', '.join(display)
       return 'top [' + display + ']'

   def is_empty(self):
       # NOTE: DO NOT EDIT THIS CODE
       # check if stack is empty
       return self.size == 0

   def push(self,item):
       # TODO: Write your code here...
       # TODO: add new node (with item) before top_node
       # TODO: update top_node and size properties

       pass # TODO: remove this line

   def pop(self):
       # TODO: Write your code here...
       # TODO: if empty, raise Exception('Empty stack: cannot pop')
       # TODO: remove top node and return its item
       # TODO: remove any links from old top_node (Hint: set to None)
       # TODO: update top_node and size properties
  
       pass # TODO: remove this line

   def top(self):
       # TODO: Write your code here...
       # TODO: if empty, raise Exception('Empty stack: no top')
       # TODO: return top_node's item

       pass # TODO: remove this line

Homework Answers

Answer #1

ANSWER:

  • I have provided the properly commented code in both text and image format so you can easily copy the code as well as check for correct indentation.
  • I have provided the output image of the code so you can easily cross-check for the correct output of the code.
  • Have a nice and healthy day!!

CODE TEXT

# sample class SLLNode, as not provided in question
class SLLNode:
def __init__(self,item):
# constructor: set properties item, next_node
self.item = item
self.next = None
  
# method get_item()
def get_item(self):
# return item value
return self.item
  
# method set_item()
def set_item(self,item):
# set item value
self.item = item
  
# method get_next()
def get_next(self):
# return next node
return self.next
  
# method set_next():
def set_next(self,node):
# set next value
self.next = node

# class SLLStack
class SLLStack:
def __init__(self):
# NOTE: DO NOT EDIT THIS CODE
# constructor: set properties top_node, size
self.top_node = None
self.size = 0
  
def __repr__(self):
# NOTE: DO NOT EDIT THIS CODE
# string representation of SLLStack object
display = []
node = self.top_node
while node != None:
display.append(str(node.get_item()))
node = node.get_next()
display = ', '.join(display)
return 'top [' + display + ']'
  
  
def is_empty(self):
# NOTE: DO NOT EDIT THIS CODE
# check if stack is empty
return self.size == 0
  
def push(self,item):
# TODO: Write your code here...
# TODO: add new node (with item) before top_node
# new node, SLLNode object with value item
node = SLLNode(item)
# seting next value of node to top_node, using set_next method
node.set_next(self.top_node)
  
# TODO: update top_node and size properties
# updating top_node to node
self.top_node = node
# updating size, by incrementing by 1
self.size += 1
  
def pop(self):
# TODO: Write your code here...
# TODO: if empty, raise Exception('Empty stack: cannot pop')
if self.size == 0:
raise Exception('Empty stack: cannot pop')
  
# TODO: remove top node and return its item
# defining next_node and assigning it next node to top node
# using get_next() method
next_node = self.top_node.get_next()
# fetching value from top_node using get_item method
top_value = self.top_node.get_item()
  
# TODO: remove any links from old top_node (Hint: set to None)
# assigning next of top_node to none, using set_next
self.top_node.set_next(None)
  
# TODO: update top_node and size properties
# updating top_node to next_node
self.top_node = next_node
# decrementing size by 1
self.size -= 1
  
# returning top_value
return top_value
  
def top(self):
# TODO: Write your code here...
# TODO: if empty, raise Exception('Empty stack: no top')
if self.size == 0:
raise Exception('Empty stack: no top')
  
# TODO: return top_node's item
# using get_item method
return self.top_node.get_item()
  
## example
# defining stack
stack = SLLStack()
# pushing values 0 to 9 in stack
for i in range(10):
stack.push(i)
  
# displaying stack
print("Initial stack:",stack)

# displaying top value
print("Top value:",stack.top())

# displaying pop value and left stack
pop = stack.pop()
print("Pop value:",pop,",Left stack:",stack)

CODE IMAGE

OUTPUT IMAGE

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line),...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line), insert each separate word into the stack, and read/print on the screen. So, if the user enters: This is a test the application output should be: test a is This. This is SLLSTACK.java below package linked_lists; public class SLLStack {    //instance variabels    private SLLNode top;    private int numOfItems;       //constructors    public SLLStack() {        top = null;   ...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(),...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(), which returns true if and only if the stack is empty; public T pop() throws StackUnderflowException, which removes and returns the top element of the stack (if the stack is empty, it throws StackUnderflowException); public T peek() throws StackUnderflowException, which returns the top element of the stack (but does not remove it; it throws exception if stack is empty); public void push(T element), which...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
Chapter 18 Lab – Design and code your own LIFO Stack using single liked list to...
Chapter 18 Lab – Design and code your own LIFO Stack using single liked list to hold a list of integers. Use the C++ “struct” structure to create your SLL nodes. Node position numbering should start with one. Your program should include the main program to test and demonstrate one function for each Stack operations including: InitStack – Initialize LIFO Stack PushStack – Add an item to top of Stack at PrintStack – Print out the Stack items PopStack –...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module Description === Your task in this prep is to implement each of the unimplemented Tree methods in this file. The starter code has a recursive template that includes the "size-one" case; you may or may not choose to use this in your final implementations. """ from __future__ import annotations from typing import Any, List, Optional class Tree: """A recursive tree...
python problem: ( use a loop to read each character from the string and insert into...
python problem: ( use a loop to read each character from the string and insert into the stack) 1. The function main a5.py continually asks the user for a string, and calls isPalindrome to check whether each string is a palindrome. A palindrome is a word or sequence that reads the same backward as forward, e.g., noon, madam or nurses run. 2. Your function must ignore spaces: when the user enters 'nurses run', the function returns True, to indicate that...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity  ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity   Code   Description   Project   File   Line   Suppression State Warning   C6385   Reading invalid data from 'DynamicStack': the readable size is '(unsigned int)*28+4' bytes, but '56' bytes may be read.   Here is the C++ code were I'm having the warning. // Sstack.cpp #include "SStack.h" // Constructor SStack::SStack(int cap) : Capacity(cap), used(0) {    DynamicStack = new string[Capacity]; } // Copy Constructor SStack::SStack(const SStack& s) : Capacity(s.Capacity), used(s.used)...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract method called makeStack that returns a Stack of Strings. Use the Stack interface as the return type, not a specific implementation! Write a class named NodeStackTest that extends your AbstractStackTest class. Implement the makeStack method to return a NodeStack. Repeat parts 1 and 2 for the Queue interface and the NodeQueue implementation. Write a new stack implementation, ArrayStack. It should be generic and use...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT