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;   ...
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 –...
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...
"""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...
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...
Please create a python module named homework.py and implement the functions outlined below. Below you will...
Please create a python module named homework.py and implement the functions outlined below. Below you will find an explanation for each function you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment. This assignment is supposed to test you on your understanding of reading and writing to a...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these classes: Product, Customer, and Store. All data members of each class should be marked as **private** (a leading underscore in the name). Since they're private, if you need to access them from outside the class, you should do so via get or set methods. Any get or set methods should be named per the usual convention ("get_" or "set_" followed by the name of...