原创。 在储存字符串的java脚本(javascript)单链表的定义中,一种插入方法:orderInset( data) 按给定字符串 data 的大小,将其放到合适的位置。这样,可以保证单链表始终是有序的。无须再
在储存字符串的java脚本(javascript)单链表的定义中,一种插入方法:orderInset( data) 按给定字符串 data 的大小,将其放到合适的位置。这样,可以保证单链表始终是有序的。无须再调用任何排序的方法。为英文文档的单词存储,提供一种有用的方法。
注意:
1. 仅适用于英文字母的字符串, 因为,汉字按UNICODE排序,似乎没有直观意义。
2. 比较两个字符串 s1 和 s2 的大小,可以直接用 s1 > s2, 如果第一个字符一样,再比较下一个字符...
3. 测试表明:如果查询方法写成:
SList.prototype.search= function (data) {
var p = this.head;
while (p.data != data && p!=null)
p = p.next;
return p;
}
则此方法不能实现所有功能。因此,改写了一下代码,以便使程序正常工作。
1. [图片] linked_list_string.png
2. [代码][JavaScript]代码
<html>
<head>
<title>Linked List</title>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
function Node(data) {
this.data = data;
this.next = null;
}
var SList =function SList() {
this.head = new Node("Dummy");
}
SList.prototype.is_empty= function (){
document.write("is_empty");
return (this.head.next == NULL);
}
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.orderInsert =function(data) {
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.traversal=function (){
var p=this.head;
while (p.next != null){
document.write( p.next.data + ", ");
p = p.next;
}
}
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 s = Array("geophysics","geology","physics",
"biology","chemistry","computer science",
"medical science","geodedic","geography");
var list = new SList();
for (var i=0; i<s.length; i++)
list.orderInsert(s[i]);
list.traversal();
var ss="geochemistry";
var p = list.search(ss);
if (p)
document.write("<br>"+p.data + " found.");
else
document.write("<br>"+ss+" not found.");
</script>
</body>
</html>
