Leetcode系列之链表(15)

2019-10-29  本文已影响0人  FisherTige_f2ef

题目:

给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是百位数...),求这个两个数的和,结果也用链表表示。

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

思路:

1.考虑进位问题,普通进位与链表尾的进位

2.链表长度不相等问题

3.使用头插法或者尾插法

4.考虑时间与空间效率问题

代码:

/**

* Definition for singly-linked list.

* public class ListNode {

*    int val;

*    ListNode next;

*    ListNode(int x) {

*        val = x;

*        next = null;

*    }

* }

*/

public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode temp = new ListNode(-1);

        ListNode head = temp;

        int count = 0;

        while(l1 != null && l2 != null){

            head.next = new ListNode((l1.val+l2.val+count)%10);

            head = head.next;

            count = (l1.val+l2.val+count)/10;

            l1 = l1.next;

            l2 = l2.next;

        }

        while(l1 != null){

            head.next = new ListNode((l1.val+count)%10);

            head = head.next;

            count = (l1.val+count)/10;

            l1 = l1.next;

        }

        while(l2 != null){

            head.next = new ListNode((l2.val+count)%10);

            head = head.next;

            count = (l2.val+count)/10;

            l2 = l2.next;

        }

        if(count == 1){

            head.next = new ListNode(1);

            head = head.next;

        }

        return temp.next;

    }

}

上一篇下一篇

猜你喜欢

热点阅读