JavaScript 基于单链表统计英语单词出现次数

作者:木棉时间:2026-10-30 09:15:22浏览:72

本文介绍如何使用JavaScript的单链表结构来统计英语单词的出现次数。通过自定义Node类和SList类,利用orderInsert方法按字母顺序插入单词并记录频次,最后遍历输出结果。该示例展示了链表在数据处理中的实际应用。

JavaScript 单链表单词统计实现

本文分享了一段使用 JavaScript 实现英语单词频率统计的代码示例。该程序利用单链表(LinkedList)结构,通过调用 orderInsert() 方法,将英文字符串按字母顺序进行存储,同时记录每个单词出现的次数。具体实现细节如下文所示。

核心代码结构


<html>
<head>
 <title>Linked List</title>
 <meta charset="utf-8">
</head>
<body>
<script type="text/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){
  document.write( 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("earthquake","prediction","geology","physics",
 "chemistry","biology","mathematics","computer","earth_science",
 "chemistry","biology","mathematics","computer","paleomagnetism",
 "topology","biology","mathematics","computer","earthquake");
 for (var i=0; i<s.length; i++)
 Slist.orderInsert(s[i]);
 Slist.traversal(); 
</script>
</body>
</html>

运行结果展示

运行效果如下:

 JavaScript 单链表单词统计实现

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

作者最新文章