Q: You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
public class AddTwoNumber {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
int sum = 0;
ListNode cur = dummy;
ListNode p1 = l1, p2 = l2;
while(p1 != null || p2 != null){
if(p1 != null) {
sum += p1.val;
p1 = p1.next;
}
if(p2 != null) {
sum += p2.val;
p2 = p2.next;
}
cur.next = new ListNode(sum % 10);
sum /= 10;
cur = cur.next;
}
if(sum == 1){
cur.next = new ListNode(1);
}
return dummy.next;
}
public static void printList(ListNode list)
{
ListNode currNode = list;
System.out.print("LinkedList: ");
// Traverse through the LinkedList
while (currNode != null) {
// Print the data at current node
System.out.print(currNode.val + " ");
// Go to next node
currNode = currNode.next;
}
}
public static void main(String args[]){
ListNode head = new ListNode(1);
ListNode second = new ListNode(5);
ListNode third = new ListNode(6);
ListNode fourth = new ListNode(9);
ListNode dummy = new ListNode(0);
//Attach them together to form a list
head.next = second;
second.next = third;
third.next = fourth;
AddTwoNumber s = new AddTwoNumber();
dummy.next = s.addTwoNumbers(head,second);
printList(dummy.next);
}
}
用linkedlist做,因为要移动指正,所以要新建三个linkedlist,p1、p2是指传进去的两个列表,cur用来返回新生成的列表。
logic:
当两个列表不为空时,不断将对应的值相加,取cur.next = 相加之后的值。cur = cur.next。cur 指针移动到下一位。sum /= 10;保留进位。最后需要检查最后一位是否还有进位。sum == 1。