How will you display a linked list from the end?
💻 coding

How will you display a linked list from the end?

1 min read 210 words
1 min read
ShareWhatsAppPost on X
  • 1To display a linked list from the end, traverse recursively until the last node is reached.
  • 2The time complexity of this method is O(n) due to visiting each element once.
  • 3The space complexity is also O(n) because of the stack formed during recursion.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To display a linked list from the end, traverse recursively until the last node is reached."

How will you display a linked list from the end?

Traverse recursively till the end of the linked list. While returning back, we can print the elements. This approach will take Time Complexity O(n) as we are traversing through each element at least once and the space complexity of O(n) as we are forming a Stack in the recursion.

Java Solution for the above problem is as below:

package askgif.linkedlist;

import java.util.Stack;

class ListNode{
 public int data;
 public ListNode next;
 ListNode(int data){
 	this.data = data;
 }
};

public class LinkedListNode {

	public static void main(String[] args) {
		
 ListNode node1 = new ListNode(1);
 ListNode node2 = new ListNode(2);
 ListNode node3 = new ListNode(3);
 ListNode node4 = new ListNode(4);
 ListNode node5 = new ListNode(5);
 ListNode node6 = new ListNode(6);
 ListNode node7 = new ListNode(7);
 ListNode node8 = new ListNode(8);
 ListNode node9 = new ListNode(9);
 ListNode node10 = new ListNode(10);
 ListNode node11 = new ListNode(11);
 
 node1.next = node2;
 node2.next = node3;
 node3.next = node4;
 node4.next = node5;
 node5.next = node6;
 node6.next = node7;
 node7.next = node8;
 node8.next = node9;
 node9.next = node10;
 node10.next = node11;
 node11.next = null;
 
		DisplayLinkedListFromEnd( node1);
		
	}

	private static void DisplayLinkedListFromEnd(ListNode node1) {
		
		if(node1 == null)
			return;
		DisplayLinkedListFromEnd(node1.next);
		System.out.println(node1.data);
	}

}
output:

11
10
9
8
7
6
5
4
3
2
1

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 7 August 2018 · 1 min read · 210 words

Part of AskGif Blog · coding

You might also like