Add Two Numbers 链表基本应用

来源:互联网 发布:办公软件应用2003 编辑:程序博客网 时间:2024/05/16 11:59

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

=============================================================================================================================

没什么说的,链表基本应用

class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode * result = l1; ListNode * temp; if (l1 == NULL && l2 == NULL) { return result; } else if (l1 == NULL) { return l2; } int added = 0; while (l1 != NULL && l2 != NULL) { l1->val += (l2->val + added); added = l1->val / 10; l1->val = l1->val % 10; l1 = l1->next; l2 = l2->next; } if (l2 != NULL) {temp = result; while (true) { if (temp->next) { temp = temp->next; }  else { break; } } temp->next = l2; l1 = l2; } while (l1 != NULL) { l1->val += added; added = l1->val / 10; l1->val = l1->val % 10; l1 = l1->next; } if (added) { temp = result; while (1) { if (temp->next) { temp = temp->next; } else { break; } } temp->next = new ListNode(added); } return result;    }};


0 0
原创粉丝点击