Core JavaScript

Reverse a Linked List

This JavaScript Reference section displays the code for an example program that shows how to reverse a linked list in JavaScript.

ReverseLinkedList.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net's Javascript</title>
		<script type="text/javascript" src="ReverseLinkedList.js"></script>
	</head>
	<body onload="Execute()">
	</body>
</html>

ReverseLinkedList.js

function Execute() {
	let qLinkedList = new CLinkedList();
	// Insert random integer values from 0 to 199
	for (let i = 0; i < 10; ++i) {
		let qNewLink = new CLink(Math.floor(200*Math.random()));
		qLinkedList.InsertAtHead(qNewLink);
	}
	qLinkedList.Print();
	qLinkedList.Reverse();
	qLinkedList.Print();
}


class CLink {
	mdData;
	mqNext = null;
	constructor(dData) {
		this.mdData = dData;
	}
}

class CLinkedList {
	mqpHead = null;
	constructor() {}
	InsertAtHead(qNewLink) {
		qNewLink.mqNext = this.mqpHead;
		this.mqpHead = qNewLink;
	}
	Reverse() {
		let qpNewHead = null;
		let qpCurr = this.mqpHead;
		while (this.mqpHead != null) {
			qpCurr = this.mqpHead;
			this.mqpHead = this.mqpHead.mqNext;
			qpCurr.mqNext = qpNewHead;
			qpNewHead = qpCurr;
		}
		this.mqpHead = qpNewHead;
	}
	Print() {
		let qNewDiv = document.createElement("div");
		let qpCurr = this.mqpHead;
		while (qpCurr != null) {
			qNewDiv.innerHTML += "[" + qpCurr.mdData + "]&#x2192;";
			qpCurr = qpCurr.mqNext;
		}
		qNewDiv.innerHTML += "null";
		let qBody = document.body;
		qBody.appendChild(qNewDiv);
	}
}

 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.