[JS算法]如何用JS实现链表和树的数据结构?

是是非非 2004-09-06 03:00:12
rt

树可以用DOM来做了,但是偶不想这样

有没有类似C++的方法?


偶只要纯算法和数据结构,不针对任何问题
...全文
453 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
BubbleInDiamond 2004-09-06
  • 打赏
  • 举报
回复
老板会说:哇塞,好厉害,我不得不给你个零分

无聊……
是是非非 2004-09-06
  • 打赏
  • 举报
回复
强!

robinzsy() 和 LxcJie(肖冲*爱*捷捷)

还有更好的吗?
ouyld 2004-09-06
  • 打赏
  • 举报
回复
LxcJie 2004-09-06
  • 打赏
  • 举报
回复
一个最简单的树的结构

<SCRIPT language="javascript">

/************树结构***************/
function TreeItem(txt)
{
this.text = txt;
this.childNodes = new Array();
this.parentNode = null;
}

TreeItem.prototype.add = function(node)
{
node.parentNode = this;
this.childNodes[this.childNodes.length] = node;
}
/************树结构***************/

/**********以下是应用*************/
TreeItem.prototype.toString = function()
{
var sumStr = "";
if(this.childNodes.length > 0)
{
sumStr += this.text + "<br>";
sumStr += getChild(this);
}
else
sumStr += this.text + "<br>";

function getChild(node)
{
var str = "";
for(var i=0; i<node.childNodes.length; i++)
{
var treeNode = node.childNodes[i];
var level = getParentLevel(treeNode);
var blankStr = makeBlank(level);
if(treeNode.childNodes.length > 0)
{
str += blankStr + treeNode.text + "<br>";
str += getChild(treeNode);
}
else
str += blankStr + treeNode.text + "<br>";
}
return str;
}

function getParentLevel(node)
{
var i=0;
var pNode = node.parentNode;
while(pNode != null)
{
i++;
pNode = pNode.parentNode;
}
return i;
}

function makeBlank(level)
{
var str = "";
for(var i=0; i<level; i++)
str += "  ";
return str;
}

return sumStr;
}

var tree = new TreeItem("1");
cTree = new TreeItem("1.1")
cTree.add(new TreeItem("1.1.1"));
cTree.add(new TreeItem("1.1.2"));
tree.add(cTree);
tree.add(new TreeItem("1.2"));
tree.add(new TreeItem("1.3"));
document.write(tree);
</SCRIPT>
robinzsy 2004-09-06
  • 打赏
  • 举报
回复
用function构造类来实现链表:

<html>
<head>
<script type="text/javascript">
function myclass(value)
{
this.data=value;
this.next=null;

}
var first=null;
var last=null;
function run()
{
a=new myclass(document.getElementById("txt").value);
if (first==null)
{
first=a;
last=a;
}
else
{
last.next=a;
last=a;
}
document.getElementById("txt").value="";
alert(a.data);
}
function show()
{
for(temp=first;temp!=null;temp=temp.next)
{
alert(temp.data);
}
}
</script>
</head>
<body>
<input type=text width=10 id="txt">
<input type=button value="add" onclick="run()">
<input type=button value="show" onclick="show()">
</body>
</html>
该代码实现点击“add”将text 中的内容加入到链表中。点击“show”将整个链表的内容输出。你可以参考一下,树结构也可以由相似方法实现。
fason 2004-09-06
  • 打赏
  • 举报
回复
DOM和C++并列吗?

87,995

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧