LeetCode #002 Add Two Numbers

来源:互联网 发布:解放台湾 知乎 编辑:程序博客网 时间:2024/04/30 00:58

002 Add Two Numbers

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

思路:
  1. 建立一个新的链表List
  2. 依次检测两个链表节点是否为空,不为空则检测值
  3. 如果检测到值,int value = val1 + val2 + remain;
  4. val1=l1->val,val2=l2->val,它们被初始化为0,remain为进位值.
  5. 将value存入List节点里
代码:
/** * 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 remain = 0;    //new list    ListNode* head = new ListNode(0);//head node,it is empty.    ListNode* p = head;    if(l1==NULL && l2==NULL){        return NULL;    }    else if(l1==NULL && l2!=NULL){        return l2;    }    else if(l1!=NULL && l2==NULL){        return l1;    }    while(l1 != NULL ||  l2 != NULL)//only two list get end,while will be finish.    {        int val1 = 0, val2 = 0;        if(l1 != NULL)        {            val1 = l1->val;        }        if(l2 != NULL)        {            val2 = l2->val;        }        int value = val1 + val2 + remain;        remain = 0;        if(value >= 10)        {            value -= 10;//value = value % 10            remain = 1;        }        //build List        ListNode * pos = new ListNode(value);        p->next = pos;        p = p->next;        if(l1 != NULL)            l1 = l1->next;        if(l2 != NULL)            l2 = l2->next;    }    /*    if ABCDE    if FGHIG    AND IF E+G>10    we need make a new node,it's val is (E+G)%10.    like this:    */    if(remain != 0)    {        ListNode* pos = new ListNode(remain);        p->next = pos;    }    return head->next;    //!!!__Don't return head because head is empty,head->next is first node with val.}};*/
知识点
  1. 如何用尾插法建立链表
  2. 同时遍历两个链表并进行相应处理(均遍历到结尾时处理才结束)
  3. 当遍历A节点时,得到需要处理A->next的信息,如何在遍历时延后一步处理。
    1. 方案1:用一个Bool量标记是否应当处理,在建表后的语句中加入处理语句
    2. 方案2:类似这种求和,将信息保留在remain中,每次加上remain,无信息则remain=0,否则remain=溢出数.
    //方案1    bool deal=false;    while(true){    ....//here you build list        if(deal){    ....//here you deal something        }    }    //方案2    int value = val1 + val2 + remain;
0 0