Leetcode add-two-numbers

来源:互联网 发布:极客大数据 编辑:程序博客网 时间:2024/06/05 00:36

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

/** * 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 *h1=l1,*h2=l2;        bool ok=true;        while(h1&&h2){            h1=h1->next;            h2=h2->next;        }        if(h2){            h1=l2;            h2=l1;            ok=false;        }        else{            h1=l1;            h2=l2;        }        if(h1){            int flag=0;            while(h2){                h1->val+=h2->val+flag;                flag=0;//要及时把进位标志清0                if(h1->val>=10){                    flag=1;                    h1->val%=10;                   }                h2=h2->next;                h1=h1->next;            }            while(h1){                h1->val+=flag;                flag=0;                if(h1->val>=10){                    flag=1;                    h1->val%=10;                   }                h1=h1->next;            }            if(flag){//首位有进位                if(ok){                    h1=l1;                }                else{                    h1=l2;                }                while(h1->next){                    h1=h1->next;                }                ListNode *p=new ListNode(flag);                p->next=h1->next;                h1->next=p;            }        }        return ok?l1:l2;    }};
0 0
原创粉丝点击