Question
package Exercise2; public class SinglyLinkedList { private class Node { int data; Node next; } private Node head; public void add(int item) { Node node
package Exercise2;
public class SinglyLinkedList {
private class Node {
int data;
Node next;
}
private Node head;
public void add(int item) {
Node node = new Node();
node.data = item;
node.next = head;
head = node;
}
public void concatenate(SinglyLinkedList other) {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = other.head;
}
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
SinglyLinkedList list1 = new SinglyLinkedList();
list1.add(1);
list1.add(2);
list1.add(3);
list1.print();
SinglyLinkedList list2 = new SinglyLinkedList();
list2.add(4);
list2.add(5);
list2.add(6);
list2.print();
list1.concatenate(list2);
list1.print();
}
}
Please add comments to my code. Like //this function does this
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started