js统计数组中单词出现次数代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了统计数组中单词出现次数的功能。

采用单链表方式实现,代码实例如下:

function Node(data) {  
  this.data = data;  
  this.frequency = 1;  
  this.next = null;   
}  
var SList = function SList() {  
  this.head = new Node("Dummy");   
}
SList.prototype.insertLast = function(data) {  
  var p = this.head;  
  while (p.next != null)   p = p.next;  
  p.next = new Node(data);  
}
SList.prototype.insertFirst = function(data) {  
  var p = new Node(data);  
  p.next = this.head.next;  
  this.head.next = p;  
}
SList.prototype.traversal = function() {  
  var p = this.head;  
  while (p.next != null) {  
    console.log(p.next.data + "(" + p.next.frequency + "), ");  
    p = p.next;  
  } 
}   
SList.prototype.orderInsert = function(data) { 
  var k = this.search(data); 
  if (k) k.frequency++; 
  else {  
    var p = new Node(data);  
    var q = this.head;  
    while (q.next != null && q.next.data < data)   q = q.next;  
    p.next = q.next;  
    q.next = p;  
  } 
} 
SList.prototype.search = function(data) {  
  var p = this.head;  
  while (p.data != data && p.next != null)   p = p.next;  
  if (p.data != data)   return null;  
  else   return p;  
}     
var Slist = new SList(); 
var s = new Array("antzone","softwhy","ant","www","url","antzone","ant","url"); 
for (var index = 0; index < s.length; index++){
  Slist.orderInsert(s[index]);
}  
Slist.traversal();

js统计数组中单词出现次数代码实例,这样的场景在实际项目中还是用的比较多的,关于js统计数组中单词出现次数代码实例就介绍到这了。

js统计数组中单词出现次数代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容