2. Add Two Numbers

来源:互联网 发布:vip域名交易 编辑:程序博客网 时间:2024/06/16 01:04

Problem:

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


题意是给出两个链表,每个链表代表一个倒序的数,例如例子里的 2 -> 4 -> 3表示的是342。还有这个数的前驱不会是0,除非这个数是0。然后要求我们求出这两个数的和。

题目比较简单,主要是一些指针的操作,因为倒序的原因,所以简单了很多,只要从链表开头一直加到结尾就好了。然后要考虑到进位的问题,所以用一个flag,等于1表示要进位,0表示不需要进位。然后有可能会遇到两个数长度不一的情况,这个时候就判断当前指针里的val值是否为NULL,是的话当前值就位0。最后,要查看flag值,是1的话,还得加一位1。代码如下:


Code:(LeetCode运行36ms)

/** * 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 = new ListNode(-1);        int flag = 0;        ListNode *preNode = result;        for (ListNode *a1 = l1, *a2 = l2; a1 != NULL || a2 != NULL; a1 = a1 == NULL ? NULL : a1 -> next,            a2 = a2 == NULL ? NULL: a2 -> next, preNode = preNode -> next) {            int v1 = a1 == NULL ? 0 : a1 -> val;            int v2 = a2 == NULL ? 0 : a2 -> val;            int addVal = (v1 + v2 + flag) % 10;            flag = (v1 + v2 + flag) / 10;            preNode -> next = new ListNode(addVal);        }        if (flag) {            preNode -> next = new ListNode(1);        }        return result -> next;    }};


原创粉丝点击