The next problem is based on Data Structure “Linked List”. It is a data structure having a collection of elements where every element has a reference pointing to the next element in the collection.Each element in linked list is called a node which has commonly two parts; the data part and the reference part which holds the link to the other node.

**Task**

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

**Sample Input**

1 2 3 4 5 |
4 2 3 4 1 |

**Sample Output**

1 |
2 3 4 1 |

So here lies your Solution .

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import java.io.*; import java.util.*; class Node { int data; Node next; Node(int d) { data = d; next = null; } } class Solution { public static Node insert(Node head,int data) { // This is the method which we have to add. Node current=head; Node temp=null; if(current==null) { temp=new Node(data); current=temp; return temp; } else { Node temp1=current; while(current.next!=null) { current=current.next; } current.next= new Node(data); current= current.next; current.data =data; return temp1; } } public static void display(Node head) { Node start = head; while(start != null) { System.out.print(start.data + " "); start = start.next; } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); Node head = null; int N = sc.nextInt(); while(N-- > 0) { int ele = sc.nextInt(); head = insert(head,ele); } display(head); sc.close(); } } |

Thanks for the visit checkout the day 16 tutorial as well.. 🙂