首页 > 代码库 > Add Two Numbers

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 /** 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         if( !l1 ) return l2;    //l1为空13         if( !l2 ) return l1;    //l2为空14         ListNode node(0);   //建立一个头结点15         ListNode* pre = &node;  //前驱节点16         int carry = 0;  //进位值17         while( l1 && l2 )  {    //当两链表所指的节点都存在时18             int sum = l1->val + l2->val + carry;    //模拟加法19             ListNode* p = new ListNode( sum%10 );20             carry = sum/10;21             pre->next = p;22             pre = p;23             l1 = l1->next;24             l2 = l2->next;25         }26         l1 = l1 ? l1 : l2;  //使l1指向不为空的链表27         while( l1 ) {   //处理进位有可能导致高位数变化28             int sum = l1->val + carry;29             ListNode* p = new ListNode( sum%10 );30             carry = sum/10;31             pre->next = p;32             pre = p;33             l1 = l1->next;34         }35         if( carry ) {   //如果依然还有进位36             ListNode* p = new ListNode(carry);37             pre->next = p;38         }39         return node.next;40     }41 };

 

Add Two Numbers