作业11.167:链表求和

来源:互联网 发布:京东咚咚工作台mac版 编辑:程序博客网 时间:2024/05/21 11:05

题目:链表求和


样例:给出两个链表3->1->5->null和5->9->2->null。返回8->0->8->null。


思路:首先写出两个链表中有空链表的情况。然后当两个链表都不为空时,相同位置的节点数相加,大于等于10时,对10求余,向后进一位,后一位加1。


代码:

class Solution {public:    /**     * @param l1: the first list     * @param l2: the second list     * @return: the sum list of l1 and l2      */    ListNode *addLists(ListNode *l1, ListNode *l2) {        // write your code here        if(l1==NULL) return l2;          if(l2==NULL) return l1;          int c=0;          int temp=0;        ListNode *first=new ListNode(0);          ListNode *p=first;          while(l1!=NULL&&l2!=NULL)          {            temp=l1->val+l2->val+c;             c=temp/10;             temp=temp%10;             p->next=new ListNode(temp);             p=p->next;             l1=l1->next;             l2=l2->next;          }          while(l1!=NULL)          {               temp=l1->val+c;               c=temp/10;               temp=temp%10;               p->next=new ListNode(temp);               p=p->next;               l1=l1->next;            }            while(l2!=NULL)              {                 temp=l2->val+c;                 c=temp/10;                 temp=temp%10;                 p->next=new ListNode(temp);                 p=p->next;                 l2=l2->next;              }              if(c!=0)               {                   p->next=new ListNode(c);                              }               return first->next;      }};


感想:我感觉这个题是这些题目中最为困难的一个,因为这道题所要考虑的情况较多,然后还要考虑进位的情况,思路还是比较清晰的,就是写代码时有些麻烦。

0 0