Merge pull request #118 from zhenchaozhu/master

add python stack simple browser
This commit is contained in:
wangzheng0822 2018-11-02 10:48:17 +08:00 committed by GitHub
commit e396d0dbe4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,75 @@
"""
a simple browser realize
Author: zhenchao.zhu
解答我们使用两个栈X Y我们把首次浏览的页面依次压入栈 X当点击后退按钮时再依次从栈 X 中出栈
并将出栈的数据依次放入栈 Y当我们点击前进按钮时我们依次从栈 Y 中取出数据放入栈 X
当栈 X 中没有数据时那就说明没有页面可以继续后退浏览了当栈 Y 中没有数据
那就说明没有页面可以点击前进按钮浏览了
"""
import sys
# 引用当前文件夹下的single_linked_list
sys.path.append('linked_stack.py')
from linked_stack import LinkedStack
#from .linked_stack import LinkedStack
class NewLinkedStack(LinkedStack):
def is_empty(self):
return not self._top
class Browser():
def __init__(self):
self.forward_stack = NewLinkedStack()
self.back_stack = NewLinkedStack()
def can_forward(self):
if self.back_stack.is_empty():
return False
return True
def can_back(self):
if self.forward_stack.is_empty():
return False
return True
def open(self, url):
print("Open new url %s" % url, end="\n")
self.forward_stack.push(url)
def back(self):
if self.forward_stack.is_empty():
return
top = self.forward_stack.pop()
self.back_stack.push(top)
print("back to %s" % top, end="\n")
def forward(self):
if self.back_stack.is_empty():
return
top = self.back_stack.pop()
self.forward_stack.push(top)
print("forward to %s" % top, end="\n")
if __name__ == '__main__':
browser = Browser()
browser.open('a')
browser.open('b')
browser.open('c')
if browser.can_back():
browser.back()
if browser.can_forward():
browser.forward()
browser.back()
browser.back()
browser.back()