From 0c7901fb38048f7425a4d8c3099578e0c70cba49 Mon Sep 17 00:00:00 2001 From: Aayush Bhan Date: Thu, 3 Oct 2019 15:10:06 +0530 Subject: [PATCH] Create Insert_tail.java Working solution for Insert a node at the tail of linked list - https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list/problem?isFullScreen=false --- .../Linked Lists/Insert_at_tail.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Data Structures/Linked Lists/Insert_at_tail.java diff --git a/Data Structures/Linked Lists/Insert_at_tail.java b/Data Structures/Linked Lists/Insert_at_tail.java new file mode 100644 index 0000000..288805c --- /dev/null +++ b/Data Structures/Linked Lists/Insert_at_tail.java @@ -0,0 +1,70 @@ +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + static class SinglyLinkedListNode { + public int data; + public SinglyLinkedListNode next; + + public SinglyLinkedListNode(int nodeData) { + this.data = nodeData; + this.next = null; + } + } + + static class SinglyLinkedList { + public SinglyLinkedListNode head; + + public SinglyLinkedList() { + this.head = null; + } + + + } + + public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException { + while (node != null) { + bufferedWriter.write(String.valueOf(node.data)); + + node = node.next; + + if (node != null) { + bufferedWriter.write(sep); + } + } + } + + // Complete the insertNodeAtTail function below. + + /* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode next; + * } + * + */ + static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) { + SinglyLinkedListNode temp = new SinglyLinkedListNode(data); + SinglyLinkedListNode curr = head; + + if(head==null){ + head = temp; + return head; + } else { + while(curr.next!=null){ + curr = curr.next; + } + curr.next = temp; + return head; + } + } + + private static final Scanner scanner = new Scanner(System.in);