leetcode兩數(shù)相加

給定兩個非空鏈表來表示兩個非負整數(shù)。位數(shù)按照逆序方式存儲,它們的每個節(jié)點只存儲單個數(shù)字。將兩數(shù)相加返回一個新的鏈表。

你可以假設除了數(shù)字 0 之外,這兩個數(shù)字都不會以零開頭。

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        # 創(chuàng)建三個指針
        p = l1;q = l2;L = head
        c = 0 # 表示進位
        while p!=None or q!=None:
            x = p.val if p!=None else 0
            y = q.val if q!=None else 0
            sum = c + x + y
            c = sum // 10
            L.next = ListNode(sum%10)
            L = L.next
            if p!=None :
                p = p.next
            if q!=None :
                q = q.next
        if c>0:
            L.next = ListNode(c)
        return head.next

java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode p = l1,q = l2,node = head;
        int c = 0;
        while(p!=null||q!=null){
            //這里避免了一個鏈表已經(jīng)遍歷到頭
            int x = (p!=null)?p.val:0;
            int y = (q!=null)?q.val:0;

            int sum = c + x + y;
            c = sum/10;
            node.next =new  ListNode(sum%10);
            node = node.next;
            if(q!=null) q=q.next;
            if(p!=null) p=p.next;
        }
        if(c>0){
            node.next = new ListNode(c);
        }
        return head.next;
    }
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容