Java Day 15 - Linked List




Complete the insert function in your editor so that it creates a new Node (pass data as the Node constructor argument) and inserts it at the tail of the linked list referenced by the head parameter. Once the new node is added, return the reference to the head node.



  1. import java.io.*;
  2. import java.util.*;
  3. class Node {
  4. int data;
  5. Node next;
  6. Node(int d) {
  7. data = d;
  8. next = null;
  9. }
  10. }
  11. class Solution {
  12. public static Node insert(Node head, int data) {
  13. if (head == null) head = new Node(data);
  14. else {
  15. Node curr = head;
  16. while (curr.next != null) curr = curr.next;
  17. curr.next = new Node(data);
  18. }
  19. return head;
  20. }
  21. public static void display(Node head) {
  22. Node start = head;
  23. while(start != null) {
  24. System.out.print(start.data + " ");
  25. start = start.next;
  26. }
  27. }
  28. public static void main(String args[]) {
  29. Scanner sc = new Scanner(System.in);
  30. Node head = null;
  31. int N = sc.nextInt();
  32. while(N-- > 0) {
  33. int ele = sc.nextInt();
  34. head = insert(head,ele);
  35. }
  36. display(head);
  37. sc.close();
  38. }
  39. }
download android app

Popular HackerRank Java Solutions








codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube