您的位置:首页 > Web前端 > JavaScript

单向链表遍历反转 Javascript实现

2015-02-04 00:00 531 查看
摘要: 单向链表遍历反转 Javascript实现

<script type="text/javascript">
<!-- one-way linkedlist reverse in javascript -->
function Node(value) {
this.value = value;
this.next = null;
}

Node.prototype.setNext = function(node) {
this.next = node;
return node;
}

Node.prototype.printList = function() {
var top = this;
while(top) {
console.log(top.value);
top = top.next;
}
}

Node.prototype.reverse = function() {
var topNode = null;
var originalTop = this;
var lastTopNode = originalTop;
while(originalTop.next) {
topNode = originalTop.next;
originalTop.setNext(originalTop.next.next);
topNode.setNext(lastTopNode);
lastTopNode = topNode;
}
return topNode;
}

var head = new Node(1);
head.setNext(new Node(2)).setNext(new Node(3)).setNext(new Node(4)).setNext(new Node(5));

head.printList();
head = head.reverse();
head.printList();
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息