码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode之链表

时间:2016-08-03 01:28:36      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

 

 

LeetCode之链表

标签:

原文地址:http://www.cnblogs.com/coffy/p/5731230.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!