您的位置:首页 > 其它

链表::循环双链表

2008-02-21 18:57 267 查看
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<title>Untitled Document</title>
</head>
<body>
<p>
循环双链表结构
</p>
<script type="text/javascript">
function cdnode(_code, _name){
this.code = _code;
this.name = _name;
this.front = this;
this.back = this;
}

function create_dclink(arr){
if (!arr || !arr.length) {
return null;
}
var head = null, _back = null;
for (var i = 0, cnt = arr.length; i < cnt; i++) {
var tmpNode = new cdnode(arr[i][0], arr[i][1]);
if (i == 0) {
head = tmpNode;
_back = tmpNode;
}
tmpNode.front = head;
head.back=tmpNode;
tmpNode.back = _back;
_back.front=tmpNode;
_back = tmpNode;
}
return head;
}

function insert_node(head, ptr, newNode){
if (head == null) {
if (newNode != null) {
newNode.back = newNode;
newNode.front = newNode;
}
return newNode;
}
if (ptr == null) {
var backNode = head.back;
backNode.front = newNode;
newNode.back = backNode;
newNode.front = head;
head.back = newNode;
return newNode;
}

var current = head;
while (current.code != ptr.code && current.front != head) {
current = current.front;
}
if (current.code == ptr.code) {
var _front = current.front;
_front.back = newNode;
newNode.back = current;
newNode.front = _front;
current.front = newNode;

}
return head;
}

function delete_node(dclink, nodeId){
if (dclink == null) {
return;
}
var ptr = dclink;

while (ptr.code != nodeId && ptr.front != dclink) {
ptr = ptr.front;
}
if (ptr.code == nodeId) {
if (ptr == dclink) {
dclink = dclink.front;
var backNode = ptr.back;
backNode.front = dclink;
dclink.back = backNode;

}
else {
var frontNode = ptr.front;
var backNode = ptr.back;
frontNode.back = backNode;
backNode.front = frontNode;
}
ptr = null;
}
return dclink;
}

function show_dclink(head){
var current = head
while (current.front!=head) {
document.writeln(current.name + "<br />");
current = current.front;
}
document.writeln(current.name + "<br />");
current = current.front;
}

var data = [[1, "beimu"], [2, "aihui"], [3, "bob"]];
var head = create_dclink(data);
head = delete_node(head, 3);
show_dclink(head);
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: