DSA Day 46/100

DSA Day 46/100

Topic: Linked List

Questions Successfully Completed: 1

1) Linked List Insertion

Easy

Linked List Insertion

Question
Input: LinkedList: 9->0->5->1->6->1->2->0->5->0 Output: 5 2 9 5 6 Explanation: Length of Link List = N = 5 9 0 indicated that 9 should be inserted in the beginning. Modified Link List = 9. 5 1 indicated that 5 should be inserted in the end. Modified Link List = 9,5. 6 1 indicated that 6 should be inserted in the end. Modified Link List = 9,5,6. 2 0 indicated that 2 should be inserted in the beginning. Modified Link List = 2,9,5,6. 5 0 indicated that 5 should be inserted in the beginning. Modified Link List = 5,2,9,5,6.  Final linked list = 5, 2, 9, 5, 6.
class Node{
    int data;
    Node next;

    Node(int x){
        data = x;
        next = null;
    }
}
class Solution
{
    //Function to insert a node at the beginning of the linked list.
    Node insertAtBeginning(Node head, int x)
    {
        Node newNode = new Node(x);
        newNode.next = head;
        head = newNode;
        return head;
    }

    //Function to insert a node at the end of the linked list.
    Node insertAtEnd(Node head, int x)
    {
        Node newNode = new Node(x);
        if(head==null){
            head = newNode;
            return head;
        }
        Node h = head;
        while(h.next!=null)
        {
            h = h.next;
        }
        h.next = newNode;
        return head;
    }
}

Thank you for reading :)