(When you write the solution, you can only use you are only using Stack ADT to s
ID: 3601308 • Letter: #
Question
(When you write the solution, you can only use you are only using Stack ADT to solve the problems, which is Pop and push, if you see it necessary isEmpty, top, do not use append and other list operations)
1. Implement (Simply your answer as a python function) a function with signature transfer(S,T) that transfers all elements from stack S onto stack T, so that the element tha starts at the top of S is first to be inserted onto T, and the element at the bottom of S ends up at the top of T.
2. Show how to use the transfer function, describe above, and two temporary stacks, to replace the contents of given stack S with those same elements, but in reversed order. (In order to get credit for this question, explain clearly how many transfers it will be needed and what each transfer dose, dont just plug in a number and few transfer operations without a clear explanation)
Explanation / Answer
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def transfer(S,T):
while not S.isEmpty():
a = S.pop();
T.push(a)
def reverse(S):
t1 = Stack()
t2 = Stack()
transfer(S,t1)
transfer(t1,t2)
transfer(t2,S)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.