Skip to content

Instantly share code, notes, and snippets.

@ikaruce
Created May 31, 2021 14:38
Show Gist options
  • Save ikaruce/71084b6a6c96f9e03d194f955daedd7d to your computer and use it in GitHub Desktop.
Save ikaruce/71084b6a6c96f9e03d194f955daedd7d to your computer and use it in GitHub Desktop.
LeetCode 2. Add Two Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = null;
ListNode c2 = null;
ListNode s = null;
ListNode p = null;
ListNode n = null;
int overflow = 0;
c1 = l1;
c2 = l2;
while(c1 != null || c2 != null){
int sum =0;
if( c1 == null ){
sum = c2.val + overflow;
}else if( c2 == null){
sum = c1.val + overflow;
}else{
sum = c1.val + c2.val + overflow;
}
if( sum > 9 ){
n = new ListNode(sum-10);
overflow = 1;
}else{
n = new ListNode(sum);
overflow = 0;
}
if( p != null ){
p.next = n;
}
p = n;
if( s == null ){
s = p;
}
c1 = (c1 == null || c1.next == null)? null: c1.next;
c2 = (c2 == null || c2.next == null)? null: c2.next;;
}
if(overflow > 0){
n = new ListNode(1);
p.next = n;
}
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment