标签:
题目:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题解:
单链表的操作,要注意链表为空时的判断
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode result = new ListNode(-1); ListNode node = result; int carry = 0; while(l1 != null || l2 != null){ int val1 = l1 == null ? 0 : l1.val; int val2 = l2 == null ? 0 : l2.val; node.next = new ListNode((val1 + val2 + carry) % 10); carry = val1 + val2 + carry >= 10 ? 1 : 0; if(l1 != null) l1 = l1.next; if(l2 != null) l2 = l2.next; node = node.next; } if(carry == 1) node.next = new ListNode(1); return result.next; } }
Reference:
http://www.cnblogs.com/springfor/p/3864493.html
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/4428095.html