链表实现两数相加
add-two-numbers
http://www.nowcoder.com/questionTerminal/56f8d422eae04f129c8e5a05299ae275
简单的进位和链表构造,只需要一个循环即可。
class Solution { public: /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { // write code here int value = 0; ListNode dummyHead(0); ListNode *p = &dummyHead; while (l1 || l2 || value != 0) { if (l1) value += l1->val, l1 = l1->next; if (l2) value += l2->val, l2 = l2->next; p = p->next = new ListNode(value % 10); value /= 10; } return dummyHead.next; } };
刷遍天下无敌手 文章被收录于专栏
秋招刷题历程