forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackAndBrowser.ts
112 lines (101 loc) · 2.31 KB
/
StackAndBrowser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* 基于单向链表实现栈结构
*/
export class Stack<T> {
private node: LinkedNode<T> | null = null
size: number = 0
public push(value: T) {
if (!value) return
const newNode = new LinkedNode(value)
if (!this.node) {
this.node = newNode
} else {
newNode.next = this.node
this.node = newNode
}
this.size++
}
public pop(): T | null {
if (!this.node) {
return null
}
const value = this.node.value
this.node = this.node.next
this.size--
return value
}
}
/**
* 单向链表
*/
class LinkedNode<T> {
value: T
next: LinkedNode<T> | null
constructor(value: T, next: LinkedNode<T> | null = null) {
this.value = value
this.next = next
}
}
/**
* 使用双栈结构实现浏览器的前进后退
*/
class Browser<T> {
// 存放后退的所有历史url
private backStack: Stack<T>
// 存放前进的所有url
private forwardStack: Stack<T>
private current: T
constructor(current: T) {
this.backStack = new Stack<T>()
this.forwardStack = new Stack<T>()
this.current = current
}
public back(): T | null {
if (this.backStack.size > 0) {
this.forwardStack.push(this.current)
this.current = this.backStack.pop()!
return this.getCurrentPage()
}
return null
}
public forward(): T | null {
if (this.forwardStack.size > 0) {
this.backStack.push(this.current)
this.current = this.forwardStack.pop()!
return this.getCurrentPage()
}
return null
}
/**
* 在网页上点击一个链接
* @param value
*/
public linkUrl(value: T) {
this.current && this.backStack.push(this.current)
this.current = value
}
public getCurrentPage(): T {
return this.current
}
}
const browser = new Browser('www.baidu.com')
browser.linkUrl('www.yuanzhoucehui.com')
browser.linkUrl('www.github.com/jsrdxzw')
// browser.back()
// www.github.com/jsrdxzw
console.log(browser.getCurrentPage())
browser.back()
// www.yuanzhucehui.com
console.log(browser.getCurrentPage())
browser.back()
// www.baidu.com
console.log(browser.getCurrentPage())
browser.back()
// www.baidu.com
console.log(browser.getCurrentPage())
browser.forward()
// www.yuanzhucehui.com
console.log(browser.getCurrentPage())
browser.forward()
// www.github.com/jsrdxzw
console.log(browser.getCurrentPage())