标签:
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
以前做过,复杂度太高
题目大意
用链表逆序表示一个非负整数,如342链表表示为2->4->3。两个非负整数链表表示形式相加求和。返回结果链表
思路
1.如果其中一个为空,直接返回不为空的链表
2.两个节点相加,结果放到第一个链表中,保存进位。一直到其中一个或者两个链表结束
3.如果第二个链表不为空,将剩余节点放到第一个链表结尾。对第一个链表进行进位处理
4.如果最后还有进位,申请一个节点,存放进位
时间复杂度为O(N)空间复杂度为O(1)
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * l1作为结果,不额外申请空间 15 * @param l1 16 * @param l2 17 * @return 18 */ 19 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 20 if(l1 == null || l2 == null) 21 return l1 == null ? l2 : l1; 22 ListNode p1 = l1; 23 ListNode p2 = l2; 24 int carry = 0; //记录进位 25 ListNode pre = null; 26 pre = l1; 27 28 //结果存放到p1中 29 while(p1 != null && p2 != null){ 30 p1.val = p2.val + p1.val + carry; 31 carry = p1.val / 10; 32 p1.val %= 10; 33 pre = p1; 34 35 p1 = p1.next; 36 p2 = p2.next; 37 }//while 38 39 if(p2 != null){ 40 p1 = pre; 41 p1.next = p2; 42 p1 = p1.next; 43 }//l2剩余节点放到l1 44 45 //对剩余节点进位处理 46 while(p1 != null){ 47 p1.val += carry; 48 carry = p1.val / 10; 49 p1.val %= 10; 50 pre = p1; 51 p1 = p1.next; 52 } 53 54 p1 = pre; 55 if(carry == 1){ 56 ListNode node = new ListNode(carry); 57 p1.next = node; 58 } 59 60 return l1; 61 } 62 }
标签:
原文地址:http://www.cnblogs.com/luckygxf/p/4409560.html