当前位置 博文首页 > jcLee95的博客:TypeScript算法专题 - blog9 - 单链表统计 : 返
李俊才
CSDN:jcLee95
邮箱:291148484@163.com
专题目录:https://blog.csdn.net/qq_28550263/article/details/115718216
【导读】:本节在前文的基础删为我们的单链表类添加统计某个元素在该链表中出现次数的方法
count()
。
这个功能比较简单,只要对列表的结点从头到尾进行一次遍历,在每到一个结点处比较该结点数据域中的内容与给定内容是否一致。如果一致则以为着该节点数据域中存储的数据匹配成功,表示统计出现次数的计数器加1。
它看起来实现后时这个样子的:
【code-1】
count(x:any):number{
/**
* 返回链表中结点的值域存储内容与x内容相同的结点的个数
* @param x {any} 用于比较的数据
* @returns counter {number} 被统计对象在链表数据域中出现的次数
*/
let counter = 0;
let pointer:Lnode = this.head.next;
while(pointer){
if(pointer.data == x){ // 当结点数据域 与 x 内容相匹配时
counter++; // 则技术
};
pointer = pointer.next;
};
return counter;
};
我们来试一试效果吧,给出下面的测试:
【test-1】
import * as slist from "./LinkList/singly_linked_list_02" // 导入单链表
let a = [1,1,2,4,5,7,5,6]
let list = new slist.LinkList(a);
console.log(list.count(1));
Out[]:
2
好像时符合预期的。不过,我们对上述测试代码略做修改:
【test-2】
import * as slist from "./LinkList/singly_linked_list_02" // 导入单链表
let a = [1,1,2,4,5,7,5,6,"1"]
let list = new slist.LinkList(a);
console.log(list.count(1));
Out[]:
3
发现结果为3。其原因在于在语句pointer.data == x
将1:number
和"1":string
认为是相等的。而在很多时候,我们是希望对类型进行严格区别的。为了达到区别的目的,可以,默认使用一个较为严格的比较模式对类型进行比较。实现代码如下:
【code-2】
count(x:any,strict:boolean=true):number{
/**
* 返回链表中结点的值域存储内容与x内容相同的结点的个数
* @param x {any} 用于比较的数据
* @param strict? {boolean} 是否开启严格模式,如果不开启严格模式在统计时相同的不同类型
* 可能同时被统计,如数字 1 和字符串 "1"
* @returns counter {number} 被统计对象在链表数据域中出现的次数
*/
let counter = 0;
let pointer:Lnode = this.head.next;
while(pointer){
if(pointer.data == x){
if(!strict){ // 不严格判断类型模式
counter++;
}
else{ // 严格判断类型模式
if(typeof(pointer.data)==typeof(x)){
counter++;
}
}
};
pointer = pointer.next;
};
return counter;
};
现在我们再来试试运行的效果:
【test-3】
import * as slist from "./LinkList/singly_linked_list_02" // 导入单链表模块2
let a = [1,1,2,4,5,7,5,5,"1",3,4,7,7,3,2,4]
let list = new slist.LinkList(a);
console.log(list.count(1,false)); // 不严格校验类型
console.log(list.count(1,true)); // 严格校验类型
Out[]:
3
2
符合我们的预期。
cs