Skip to main content

Reversal order of linked list using recursion in typescript

Ts program for Reversal order of linked list using recursion. Here problem description and other solutions.

// TypeScript program for
// Print reverse of a linked list without actually reversing

// Linked list node
class LinkNode
{
	public data: number;
	public next: LinkNode;
	constructor(data: number)
	{
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	public head: LinkNode;
	public tail: LinkNode;
	constructor()
	{
		this.head = null;
		this.tail = null;
	}
	// Add new Node at end of linked list 
	public addNode(data: number)
	{
		var node = new LinkNode(data);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			// Append the node at last position
			this.tail.next = node;
		}
		this.tail = node;
	}
	// Display reversal view of linked list using recursion
	public printReverse(node: LinkNode)
	{
		if (node == null)
		{
			return;
		}
		// Visit to next node
		this.printReverse(node.next);
		// Display node value
		console.log("  " + node.data);
	}
	public static main(args: string[])
	{
		var sll = new SingleLL();
		//  1 → 2 → 8 → 4 → 9 → 6 → NULL
		sll.addNode(1);
		sll.addNode(2);
		sll.addNode(8);
		sll.addNode(4);
		sll.addNode(9);
		sll.addNode(6);
		// Reversal view
		// 6 9 4 8 2 1
		sll.printReverse(sll.head);
	}
}
SingleLL.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

  6
  9
  4
  8
  2
  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