2. Add Two Numbers
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.链表长度相同时,且最后一个节点相加有进位的情况;
3.链表长度不等,短链表最后一位有进位的情况,且进位后长链表也有进位的情况;
方法一:待优化
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1==null){ return l2; } if(l2==null){ return l1; } int len1 = getLength(l1); int len2 = getLength(l2); ListNode head = null; ListNode plus = null; if(len1>=len2){ head = l1; plus = l2; }else{ head = l2; plus = l1; } ListNode p = head; int carry = 0; int sum = 0; while(plus!=null){ sum = p.val + plus.val+carry; carry = sum/10; p.val = sum%10; if(p.next==null&&carry!=0){ ListNode node = new ListNode(carry); p.next = node; carry = 0; } p = p.next; plus = plus.next; } while(p!=null&&carry!=0){ sum = p.val+carry; carry = sum/10; p.val = sum%10; if(p.next==null&&carry!=0){ ListNode node = new ListNode(carry); p.next = node; carry=0; } p = p.next; } return head; } public int getLength(ListNode l){ if(l==null){ return 0; } int len = 0; while(l!=null){ ++len; l = l.next; } return len; } }
时间: 2024-10-01 09:13:15