[LeetCode] Add Two Numbers

来源:互联网 发布:中岛美嘉长相知乎 编辑:程序博客网 时间:2024/05/01 05:02

问题:

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

分析:

非常简单一道题。我居然还没有一次过!真是想自残。。

代码:

class Solution {public:ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {ListNode *fakeHead = new ListNode (-1);ListNode *current = fakeHead;int carry = 0;while (l1 || l2 || carry != 0) {int left = l1 ? l1->val : 0;int right = l2 ? l2 ->val : 0;int sum = right + left + carry;current->next = new ListNode(sum % 10);carry = sum / 10;l1 = !l1 ? NULL : l1->next;l2 = !l2 ? NULL : l2->next;current = current->next;}ListNode *head = fakeHead->next;delete fakeHead;return head;}};



0 0
原创粉丝点击