码迷,mamicode.com
首页 > 编程语言 > 详细

单向链表遍历反转 Javascript实现

时间:2015-02-04 21:58:39      阅读:288      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!