js統計陣列中單詞出現次數程式碼例項

admin發表於2017-04-15

分享一段程式碼例項,它實現了統計陣列中單詞出現次數的功能。

採用單連結串列方式實現,程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
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();

相關文章