The code is for adding two numbers represented as linked lists in reverse order. Each node in the linked list represents a digit of the number, and the digits are stored in reverse order, i.e., the least significant digit is at the head of the list.
The AddTwo_LinkedList class has a nested node class, which represents a node in the linked list. Each node has a value (val) and a reference to the next node (next). The AddTwo_LinkedList class has several methods:
public class AddTwo_LinkedList { class node { int val; node next; public node(int val) { this.val = val; } } void printlist(node head) { while (head != null) { System.out.print(head.val + " "); head = head.next; } } node head1, head2, res; int d; void push(int val, int list) { node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = res; res = newnode; } } void addsamesize(node n, node m) { if (n == null) return; addsamesize(n.next, m.next); int sum = n.val + m.val + d; d = sum / 10; sum = sum % 10; push(sum, 3); } node cur; void propogatecarry(node head1) { if (head1 != cur) { propogatecarry(head1.next); int sum = d + head1.val; d = sum / 10; sum %= 10; push(sum, 3); } } int getsize(node head) { int count = 0; while (head != null) { count++; head = head.next; } return count; } void addlists() { if (head1 == null) { res = head2; return; } if (head2 == null) { res = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); if (size1 == size2) { addsamesize(head1, head2); } else { if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.abs(size1 - size2); node temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } addsamesize(cur, head2); propogatecarry(head1); } if (d > 0) push(d, 3); } public static void main(String args[]) { AddTwo_LinkedList list = new AddTwo_LinkedList(); list.head1 = null; list.head2 = null; list.res = null; list.d = 0; int arr1[] = { 1, 2, 3, 4, 5 }; int arr2[] = { 1, 2, 3, 4, 5 }; for (int i = arr1.length - 1; i >= 0; --i) { list.push(arr1[i], 1); } for (int i = arr2.length - 1; i >= 0; --i) { list.push(arr2[i], 2); } list.addlists(); list.printlist(list.res); } }
2 4 6 9 0
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions