分享

2  LeetCode | Add Two Numbers

 雪柳花明 2016-09-27

题目:

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. /** 
  2.  * Definition for singly-linked list. 
  3.  * struct ListNode { 
  4.  *     int val; 
  5.  *     ListNode *next; 
  6.  *     ListNode(int x) : val(x), next(NULL) {} 
  7.  * }; 
  8.  */  
  9. class Solution {  
  10. public:  
  11.     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {  
  12.         int carry = 0;  
  13.         ListNode* tail = new ListNode(0);  
  14.         ListNode* ptr = tail;  
  15.           
  16.         while(l1 != NULL || l2 != NULL){  
  17.             int val1 = 0;  
  18.             if(l1 != NULL){  
  19.                 val1 = l1->val;  
  20.                 l1 = l1->next;  
  21.             }  
  22.               
  23.             int val2 = 0;  
  24.             if(l2 != NULL){  
  25.                 val2 = l2->val;  
  26.                 l2 = l2->next;  
  27.             }  
  28.               
  29.             int tmp = val1 + val2 + carry;  
  30.             ptr->next = new ListNode(tmp % 10);  
  31.             carry = tmp / 10;  
  32.             ptr = ptr->next;  
  33.         }  
  34.           
  35.         if(carry == 1){  
  36.             ptr->next = new ListNode(1);  
  37.         }  
  38.         return tail->next;  
  39.     }  
  40. };  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多