May 14, 2020

Sum up two Node to one in java


Our Idea is to sum up each elements in the given two nodes and create a new node.

/**
 * Sum up two Node to one in java
 */
package com.leetcode.algorithms;

/**
 * @author Cfed kozhikode
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Solution s = new Solution();

System.out.println(989+989);

ListNode l1 = new ListNode(9);
l1.next = new ListNode(9);
l1.next.next = new ListNode(9);

ListNode l2 = new ListNode(1);
/* l2.next = new ListNode(8);
l2.next.next = new ListNode(9);*/

ListNode a = s.addTwoNumbers(l1, l2);

// System.out.println(a);

while(a!=null) {
System.out.print(a.val+" ");
a=a.next;
}

}

}


package com.leetcode.algorithms;
/**
 * 
 * @author Bithesh
 *
 */
class Solution {

private ListNode parentNode = null;

private int carryforward = 0;

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

int val1 = (null != l1) ? l1.val : 0;
int val2 = (null != l2) ? l2.val : 0;
int sum = val1 + val2 + carryforward;
carryforward = sum / 10;
int value = sum % 10;
parentNode = insertValue(parentNode, value);

ListNode n1 = (l1 == null || l1.next == null) ? null : l1.next;
ListNode n2 = (l2 == null || l2.next == null) ? null : l2.next;

if (n1 != null || n2 != null) {
addTwoNumbers(n1, n2);
}else if (carryforward > 0) {
parentNode = insertValue(parentNode, carryforward);
carryforward = 0;
}
return parentNode;
}

private ListNode insertValue(ListNode node, int data) {
if (node == null) {
return new ListNode(data);
} else {
node.next = insertValue(node.next, data);
}
return node;
}
}

/**
 * 
 */
package com.leetcode.algorithms;

/**
 * @author Bithesh
 *
 */
public class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments