(算法分析Week5)Add Two Numbers[Medium]

来源:互联网 发布:密山市知一派出所 编辑:程序博客网 时间:2024/06/06 01:00

2. Add Two Numbers

Description

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

Solution

考察对链表的基本操作——遍历。写的时候为了节省空间,没有开辟新的空间,只是在原来的基础上进行加减。需要注意的是两个数位数不同和需要进位的情况。while循环遍历,直到某个链表遍历完成,再考虑进位情况,链接剩下的那个表即可。此题不算难,考虑清楚再写,一次过(虽然效率有点低)

Complexity analysis

O(n+m)

Code

/** * 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) {        int carry = 0;        ListNode* result = l1;        while(1) {            if (carry) {                l1 -> val += 1;                 carry = 0;            }            l1 -> val += l2 -> val;            if (l1 -> val >= 10) {                carry = 1;                l1 -> val -= 10;            }            if (l1 -> next == NULL || l2 -> next == NULL)                break;            l1 = l1 -> next;            l2 = l2 -> next;        }        if (l1 -> next == NULL && l2 -> next) {            l1 -> next = l2 -> next;        }        ListNode* temp = l1 -> next;        while(l1 -> next) {            if (carry) {                l1 -> next -> val += 1;                carry = 0;                if (l1 -> next -> val >= 10) {                    carry = 1;                    l1 -> next -> val -=10;                }            }            l1 = l1 -> next;        }        if (carry) {            l1 -> next = new ListNode(1);        }        return result;    }};

Result

这里写图片描述

原创粉丝点击