单向链表遍历反转 Javascript实现

原创
2015/02/04 20:40
阅读数 1.8K
<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>


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
7 收藏
1
分享
返回顶部
顶部