标签:
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
自己代码有问题,有需要修改,暂且先贴上
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 ListNode head = null; 12 ListNode p = null; 13 14 int resultVal; 15 int flag = 0; 16 if( l2 == null ) 17 head = l1; 18 if( l1 == null ) 19 head = l2; 20 //head.val = l1.val + l2.val ; 21 head.next = p; 22 while(l1.next != null && l2.next != null){ 23 p.val = (l1.val + l2.val + flag )%10; 24 flag = (l1.val + l2.val )/10; 25 p = p.next; 26 l1 = l1.next ; 27 l2 = l2.next ; 28 } 29 if (l1.next == null && l2.next != null){ 30 p.val = l2.val + flag; 31 p.next = l2.next ; 32 } 33 if (l1.next != null && l2.next == null){ 34 p.val = l1.val +flag; 35 p.next = l1.next ; 36 } 37 38 return head; 39 } 40 }
除了这么做,还可以用三指针同时进行,代码会简洁很多。
1 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 int carry =0; 4 5 ListNode newHead = new ListNode(0); 6 ListNode p1 = l1, p2 = l2, p3=newHead; 7 8 while(p1 != null || p2 != null){ 9 if(p1 != null){ 10 carry += p1.val; 11 p1 = p1.next; 12 } 13 14 if(p2 != null){ 15 carry += p2.val; 16 p2 = p2.next; 17 } 18 19 p3.next = new ListNode(carry%10); 20 p3 = p3.next; 21 carry /= 10; 22 } 23 24 if(carry==1) 25 p3.next=new ListNode(1); 26 27 return newHead.next; 28 } 29 }
标签:
原文地址:http://www.cnblogs.com/myshuangwaiwai/p/4458435.html