Answer to Question #300232 in Java | JSP | JSF for Akash srivastava

Question #300232

Given a singly linked list and an element K, your task is to insert the element at the tail of the linked list.

Input

User Task:

Since this will be a functional problem, you don't have to take input. You just have to complete the function addElement() that takes head node and the integer K as a parameter.


Constraints:

1 <=N<= 1000

1 <=K, value<= 1000

Output

Return the head of the modified linked list


1
Expert's answer
2022-02-20T09:22:24-0500
public class Main {
    public static Node addElement(Node head, int k) {
        if (head == null) {
            head = new Node(k);
        } else {
            Node node = head;
            while (node.next != null) {
                node = node.next;
            }
            node.next = new Node(k);
        }
        return head;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS