Write a Java function that add two circular linked list and create a new linked list fromit.The addition will be done as following exampleL1: 2 – 4 – 6 – 7 – 9L2 : 5 – 3 – 12 – 11 – 45-------------------------------L3 : (2 + 3 = 5 , 4 + 12 = 16, 6 + 11 = 17, 7 + 45 = 52, 9 + 5 = 14 )All are circular linked lis
Question
Write a Java function that add two circular linked list and create a new linked list fromit.The addition will be done as following exampleL1: 2 – 4 – 6 – 7 – 9L2 : 5 – 3 – 12 – 11 – 45-------------------------------L3 : (2 + 3 = 5 , 4 + 12 = 16, 6 + 11 = 17, 7 + 45 = 52, 9 + 5 = 14 )All are circular linked lis
Solution
Here is a Java function that adds two circular linked lists and creates a new linked list from it:
class Node {
int data;
Node next;
}
public Node addTwoLists(Node first, Node second) {
Node res = null;
Node prev = null;
Node temp = null;
int carry = 0, sum;
while (first != null || second != null) {
sum = carry + (first != null ? first.data : 0) + (second != null ? second.data : 0);
carry = (sum >= 10) ? 1 : 0;
sum = sum % 10;
temp = new Node();
temp.data = sum;
if (res == null) {
res = temp;
} else {
prev.next = temp;
}
prev = temp;
if (first != null) {
first = first.next;
}
if (second != null) {
second = second.next;
}
}
if (carry > 0) {
temp.next = new Node();
temp.next.data = carry;
}
return res;
}
This function creates a new linked list node by node, adding the corresponding nodes in the two input lists. If the sum of two nodes is greater than 10, it carries over the value to the next node. The new list is returned as the result.
Please note that this function assumes that the input linked lists are of the same length. If they are not, you would need to modify the function to handle this case. Also, this function does not handle the circular aspect of the linked lists. You would need to add additional logic to make the resulting linked list circular if that is required.
Similar Questions
Q1. How to implement circular linked list in Java ?
Given a sorted circular linked list of length n, the task is to insert a new node in this circular list so that it remains a sorted circular linked list.Example 1:
What is meant by circular linked list? Write an algorithmto insert a node at the end in a circular linked list.1 2 3
What is a circular linked list?A linked list where the last node points to None.A linked list where each node points to the previous and the next node.A linked list where there is a loop in the list.A linked list where each node points to the next node, and the last node points to the first node.
What is meant by circular linked lis
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.