Skip to main content

Find second last element of linked list in node js

Js program for Find second last element of linked list. Here more information.

// Node JS program for
// Find the second last node of a linked list

// Node of Linked List
class LinkNode
{
	constructor(data)
	{
		// Set node value
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	constructor()
	{
		this.head = null;
		this.tail = null;
	}
	// Add new node at the end of linked list
	insert(value)
	{
		// Create a new node
		var node = new LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			this.tail.next = node;
		}
		this.tail = node;
	}
	// Display linked list element
	display()
	{
		if (this.head == null)
		{
			return;
		}
		var temp = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			process.stdout.write(temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		process.stdout.write("null\n");
	}
	//Find the second last node of a linked list
	secondLast()
	{
		var node = this.head;
		if (node == null)
		{
			process.stdout.write("Empty linked list");
		}
		else if (node.next == null)
		{
			process.stdout.write("Only one node in this linked list");
		}
		else
		{
			// Find second last node
			while (node.next != null && node.next.next != null)
			{
				// Visit to second next node
				node = node.next.next;
			}
			console.log("Second last element is : " + node.data);
		}
	}
}

function main()
{
	var sll = new SingleLL();
	// Add linked list node
	sll.insert(6);
	sll.insert(3);
	sll.insert(2);
	sll.insert(7);
	sll.insert(1);
	sll.insert(9);
	console.log("Linked List");
	// 6 → 3 → 2 → 7 → 1 → 9 → null
	sll.display();
	sll.secondLast();
}
// Start program execution
main();

Output

Linked List
6 → 3 → 2 → 7 → 1 → 9 → null
Second last element is : 1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment