var ATOM=0;
var LIST=1;
//广义表的存储结构
function ListNode(){
//标识位
this.tag=undefined;
//原子结点的值域
this.atom=null;
//列表结点的值域
this.ptr={
hp:null,
tp:null
};
}
//创建广义表
ListNode.prototype.createList=function(string){
string=string.trim();
//创建单原子广义表
var q;
if(/^[\w-]+$/.test(string)){//含有单字符
this;tag=ATOM;
this.atom=string;
}else{
this.tag=LIST;
var p =this;
//去掉最外层括号(和)
var sub=string.substr(1,string.length-2);
do{
var h,
i=0,
k=0,
n=sub.length,
ch;
do{
ch=sub[i++];
if(ch=='('){
++k;
}else if(ch==')'){
--k;
}
}while(i<n&&(ch!=','||k!=0));
//i为第一个逗号分隔索引
if(i<n){
h=sub.substr(0,i-1);//每次遍历取出第一个结点,无论是原子还是列表
sub=sub.substr(i,n-i);
}else{//最后一组
h=sub;
sub='';
}
if(h==='()'){//空子表无表头结点
p.ptr.hp=null;
}else{//创建表头结点
this.createList.call((p.ptr.hp=new ListNode()),h);
}
q=p;
//创建表尾结点
if(sub){
p=new ListNode();
p.tag=LIST;
q.ptr.tp=p;
}
}while(sub);
q.ptr.tp=null;
}
};
//求广义表的深度
ListNode.prototype.depth=function(){
return getDepth(this);
}
function getDepth(list){//深度为括号的重数,也可理解为左括号出现的个数
if(!list){
return 1;
}else if(list.tag===ATOM){
return 0;
}else {
var m=getDepth(list.ptr.hp)+1;
var n=getDepth(list.ptr.tp);
return m>n?m:n;
}
}
var node=new ListNode();
node.createList('((),(a),(b,(c,d,e)))');
alert(node.depth());//5
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var ATOM=0;
var LIST=1;
//广义表的存储结构
function ListNode(){
//标识位
this.tag=undefined;
//原子结点的值域
this.atom=null;
//列表结点的值域
this.ptr={
hp:null,
tp:null
};
}
//创建广义表
ListNode.prototype.createList=function(string){
string=string.trim();
//创建单原子广义表
var q;
if(/^[\w-]+$/.test(string)){//含有单字符
this.tag=ATOM;
this.atom=string;
}else{
this.tag=LIST;
var p =this;
//去掉最外层括号(和)
var sub=string.substr(1,string.length-2);
do{
var h,
i=0,
k=0,
n=sub.length,
ch;
do{
ch=sub[i++];
if(ch=='('){
++k;
}else if(ch==')'){
--k;
}
}while(i<n&&(ch!=','||k!=0));
//i为第一个逗号分隔索引
if(i<n){
h=sub.substr(0,i-1);//每次遍历取出第一个结点,无论是原子还是列表
sub=sub.substr(i,n-i);
}else{//最后一组
h=sub;
sub='';
}
if(h==='()'){//空子表无表头结点
p.ptr.hp=null;
}else{//创建表头结点
this.createList.call((p.ptr.hp=new ListNode()),h);
}
q=p;
//创建表尾结点
if(sub){
p=new ListNode();
p.tag=LIST;
q.ptr.tp=p;
}
}while(sub);
q.ptr.tp=null;
}
};
//求广义表的深度
ListNode.prototype.depth=function(){
return getDepth(this);
}
function getDepth(list){//深度为括号的重数,也可理解为左括号出现的个数
if(!list){
return 1;
}else if(list.tag===ATOM){
return 0;
}else {
var m=getDepth(list.ptr.hp)+1;
var n=getDepth(list.ptr.tp);
return m>n?m:n;
}
}
var node=new ListNode();
node.createList('((),(a),(b,(c,d,e)))');
alert(node.depth());//5
</script>
</body>
</html>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有