Angular学习笔记77:在Angular项目中实现数据结构-栈

栈是一种特殊的列表,只能通过栈顶去访问栈内的元素,具有先进后出的特性。

创建一个 “栈” 服务

执行命令:

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());
  }

}

执行结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iNc7g4w9-1573631590200)(evernotecid://621D2FF6-4E72-4E02-9043-55F31F42819B/appyinxiangcom/22553815/ENResource/p888)]

因为最后执行了clear() 方法,所以在clear() 方法之后执行的peek()方法查找不到元素,所以是undefined,此时栈的长度也为0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值