栈是一种特殊的列表,只能通过栈顶去访问栈内的元素,具有先进后出的特性。
创建一个 “栈” 服务
执行命令:
dataStore git:(master) ✗ ng g s stack
CREATE src/app/dataStore/stack.service.spec.ts (328 bytes)
CREATE src/app/dataStore/stack.service.ts (134 bytes)
实现栈的各种方法
- 进栈(push)方法
public push(item) {
this.dataStore[this.top++] = item;
}
- 出栈(pop)方法
public pop() {
return this.dataStore[--this.top];
}
- 查看当前栈中有几个元素
public length() {
return this.top;
}
- 查看当前栈顶的元素
public peek() {
return this.dataStore[this.top - 1];
}
- 清空栈中所有元素
public clear() {
this.top = 0;
}
综上"栈"的实现
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Stack {
private dataStore = [];
private top = 0;
constructor() {
}
// 进栈
public push(item) {
this.dataStore[this.top++] = item;
}
// 出栈
public pop() {
return this.dataStore[--this.top];
}
// 查看栈顶元素
public peek() {
return this.dataStore[this.top - 1];
}
// 查看栈的长度
public length() {
return this.top;
}
// 清空栈
public clear() {
this.top = 0;
}
}
验证一下
- 在某一个组件中声明一个栈:
import {Component, OnInit} from '@angular/core';
import {StackService} from '../dataStore/stack.service';
@Component({
selector: 'app-introduce',
templateUrl: './introduce.component.html',
styleUrls: ['./introduce.component.less']
})
export class IntroduceComponent implements OnInit {
public demoStack = new StackService();
constructor() {
}
ngOnInit() {
}
}
- 在这个组件中调用栈的各种方法
import {Component, OnInit} from '@angular/core';
import {Stack} from '../dataStore/stack';
import {StackService} from '../dataStore/stack.service';
@Component({
selector: 'app-introduce',
templateUrl: './introduce.component.html',
styleUrls: ['./introduce.component.less']
})
export class IntroduceComponent implements OnInit {
public demoStack = new StackService();
constructor() {
}
ngOnInit() {
this.demoStack.push('demo1');
this.demoStack.push('demo2');
this.demoStack.push('demo3');
this.demoStack.push('demo4');
console.log(this.demoStack.peek());
const popItem = this.demoStack.pop();
console.log(popItem);
console.log(this.demoStack.peek());
console.log(this.demoStack.length());
this.demoStack.clear();
console.log(this.demoStack.peek());
console.log(this.demoStack.length());
}
}
执行结果:
因为最后执行了clear() 方法,所以在clear() 方法之后执行的peek()方法查找不到元素,所以是undefined,此时栈的长度也为0。