UNPKG

1.29 kBPlain TextView Raw
1import { Collection } from "../Collection";
2import LinkList from "../linklist/LinkList";
3export class Stack<T> extends Collection<T> {
4 private linkList: LinkList<T>;
5 constructor(){
6 super();
7 this.linkList = new LinkList();
8 }
9 /**
10 * 压栈
11 * @param node
12 */
13 public push(node: T){
14 return this.linkList.append(node);
15 }
16
17 /**
18 * 出栈
19 *
20 */
21 public pop(){
22 const node = this.linkList.pop();
23 if (node) {
24 return node.Value;
25 }
26 return null;
27 }
28
29 /**
30 * 查看栈顶元素
31 */
32 public peek(){
33 if (!this.linkList.getTailNode()){
34 return null;
35 }
36 return this.linkList.getTailNode().Value;
37 }
38
39 /**
40 * 空栈
41 */
42 public isEmpty(){
43 return !this.linkList.getTailNode();
44 }
45
46 public toString(){
47 return this.linkList.toString();
48 }
49
50 protected __iterate(fn: (item: T, index: number) => void): void {
51 let temp = this.linkList.getHeadNode(),
52 index = 0;
53 while (temp){
54 fn(temp.Value, index);
55 index++;
56 temp = temp.Next;
57 }
58 }
59
60 public toArray(){
61 return super.toArray().reverse();
62 }
63}
64
65export default Stack;