首页 > 编程语言 > 详细

单向链表遍历反转 Javascript实现

时间:2015-02-04 21:58:16      阅读:552      评论:0      收藏:0      [点我收藏+]
<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>


单向链表遍历反转 Javascript实现

原文:http://my.oschina.net/gengjie/blog/375446

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!