github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/datastructures/stack/stack_test.go (about)

     1  package stack
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  )
     7  
     8  func TestStack(t *testing.T) {
     9  	s := New()
    10  	s.Push(5)
    11  	s.Push(4)
    12  	s.Push(3)
    13  	s.Push(2)
    14  	s.Pop()
    15  
    16  	t.Log(s)
    17  }
    18  
    19  func TestArrayStack(t *testing.T) {
    20  	s := NewArrayStack()
    21  	//s.Push(5)
    22  	//s.Push(4)
    23  	s.Push(3)
    24  	s.Push(2)
    25  	s.Pop()
    26  	s.Pop()
    27  	t.Log(s)
    28  	t.Log(s.Peek())
    29  }
    30  
    31  // 双栈的的应用
    32  // 1. 浏览器前一页 后一页
    33  // 2. 命令设计模式中的 undo redo
    34  // 3. 四则运算 2+3*9-1 这种, 数字和运算符号,各用一个栈,
    35  // 如果比运算符栈顶元素的优先级高,就将当前运算符压入栈;如果比运算符栈顶元素的优先级低
    36  //	或者相同,从运算符栈中取栈顶运算符,从操作数栈的栈顶取 2 个操作数,然后进行计算,再
    37  //	把计算完的结果压入操作数栈,继续比较
    38  
    39  type Browser struct {
    40  	back, forward IStack
    41  }
    42  
    43  func NewBrowser() *Browser {
    44  	return &Browser{
    45  		back:    NewArrayStack(),
    46  		forward: New(),
    47  	}
    48  }
    49  
    50  func (b *Browser) CanBack() bool {
    51  	return !b.back.IsEmpty()
    52  }
    53  
    54  func (b *Browser) CanForward() bool {
    55  	return !b.forward.IsEmpty()
    56  }
    57  func (b *Browser) Open(addr string) {
    58  	fmt.Printf("Open new addr %+v\n", addr)
    59  	b.forward.Flush()
    60  }
    61  
    62  func (b *Browser) Forward() {
    63  	if b.CanForward() {
    64  		top := b.forward.Pop()
    65  		b.back.Push(top)
    66  		fmt.Printf("forward to %+v\n", top)
    67  	}
    68  }
    69  func (b *Browser) Back() {
    70  	if b.CanBack() {
    71  		top := b.back.Pop()
    72  		b.forward.Push(top)
    73  		fmt.Printf("back to %+v\n", top)
    74  	}
    75  }
    76  
    77  func (b *Browser) PushBack(addr string) {
    78  	b.back.Push(addr)
    79  }
    80  func TestStack_Browser(t *testing.T) {
    81  	b := NewBrowser()
    82  	b.PushBack("www.qq.com")
    83  	b.PushBack("www.baidu.com")
    84  	b.PushBack("www.sina.com")
    85  	if b.CanBack() {
    86  		b.Back()
    87  	}
    88  	if b.CanForward() {
    89  		b.Forward()
    90  	}
    91  	if b.CanBack() {
    92  		b.Back()
    93  	}
    94  	if b.CanBack() {
    95  		b.Back()
    96  	}
    97  	if b.CanBack() {
    98  		b.Back()
    99  	}
   100  	b.Open("www.taobao.com")
   101  	if b.CanForward() {
   102  		b.Forward()
   103  	}
   104  }