Question: 3 . def merge ( stack 1 : ListStack, stack 2 : ListStack ) ListStack: merge ( ) function merges two sorted ListStacks into one.

3. def merge(stack1: ListStack, stack2: ListStack) ListStack: merge() function merges two sorted ListStacks into one. Test case: stack1: stack2: 134572689
This function should return 123456789
(**By the way we have to use this way to solve the problem**):
class LinkedStack:
def __init__(self):
#underlying data structure is a linked list
self.stack = LinkedList()
"""return the number of elements in this stack"""
def __len__(self):
return self.stack.__len__()
"""return True if empty, False otherwise"""
def is_empty(self):
return self.stack.is_empty()
"""return top element"""
def top(self):
return self.stack.first()
"""add e to the top of the stack"""
def push(self, e):
self.stack.add_first(e)
"""remove and return the top element"""
def pop(self):
return self.stack.remove_first()
"""return a string representation of this stack"""
def __str__(self):
return self.stack.__str__()
class ListStack:
def __init__(self):
#underlying data structure is a list
self.stack = list()
"""return the number of elements in this stack"""
def __len__(self):
return len(self.stack)
"""return True if empty, False otherwise"""
def is_empty(self):
return len(self.stack)==0
"""return top element"""
def top(self):
if self.is_empty():
return None
return self.stack[-1]
"""add e to the top of the stack"""
def push(self, e):
self.stack.append(e)
"""remove and return the top element"""
def pop(self):
if self.is_empty():
return None
return self.stack.pop()
"""return a string representation of this stack"""
def __str__(self):
display = self.stack +[]
display.reverse()
return str(display)
if __name__=='__main__':
# create a linkedstack
s1= LinkedStack()
# insert 1,2,3,4,5
for e in (1,2,3,4,5):
s1.push(e)
print(s1)
# then remove everything
while not s1.is_empty():
s1.pop()
print(s1)
s2= ListStack()
for e in (1,2,3,4,5):
s2.push(e)
print(s2)
while not s2.is_empty():
s2.pop()
print(s2)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!