leetcode(medium)_2

leetcode2

  • 题目描述
  • 解答

题目描述

两个链表每个节点的数相加 得到新的链表

解答

逐位相加(注意最后一位如果有进位也要考虑)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *result = NULL;
        result = new ListNode(0);
        ListNode *cur = result;
        int tmp = 0;
        while(l1 != NULL || l2 != NULL || tmp){
            int sum = (l1 ? l1 -> val : 0) + (l2 ? l2 -> val : 0) + tmp;
            tmp = sum/10;
            if(l1)
                l1 = l1 -> next;
            if(l2)
                l2 = l2 -> next;
            cur -> next = new ListNode(sum%10);
            cur = cur -> next;
        }
    return result -> next;
    }
};

result表示头节点
用cur进行链表的构造

你可能感兴趣的:(leetcode,水)