Add two numbers represented by linked lists
2012-11-06 13:43
344 查看
#include <iostream> #include <string> struct node { int data; node* next; }; void push(node** head_ref, int new_data) { node* new_node = new node(); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node; }; int getSize(node* n) { int size = 0; while(n) { n = n->next; size++; } return size; }; node* addSameSize(node* l1, node* l2, int* carry) { if (l1 == NULL) return NULL; int sum; node* result = new node(); result->next = addSameSize(l1->next, l2->next, carry); sum = l1->data + l2->data + *carry; *carry = sum / 10; result->data = sum % 10; return result; }; void swapPointer(node** n1, node** n2) { node* t = *n1; *n1 = *n2; *n2 = t; }; void addCarryToRemaining(node* l1, node* cur, int* carry, node** result) { int sum; if (l1 != cur) { addCarryToRemaining(l1->next, cur, carry, result); sum = l1->data + *carry; *carry = sum / 10; sum %= 10; push(result, sum); } }; void addList(node* l1, node* l2, node** result) // result should be passed as pointer to pointer { if (l1 == NULL) { *result = l2; return; } if (l2 == NULL) { *result = l1; return; } int size1 = getSize(l1); int size2 = getSize(l2); int carry = 0; if (size1 == size2) *result = addSameSize(l1, l2, &carry); else { int diff = std::abs(size1 - size2); if (size1 < size2) swapPointer(&l1, &l2); node* cur; for (cur = l1; diff--; cur = cur->next); *result = addSameSize(cur, l2, &carry); // add carry to remaining addCarryToRemaining(l1, cur, &carry, result); if (carry) push(result, carry); } }; void printList(node* n) { while (n) { std::cout << n->data << " "; n = n->next; } std::cout << "\n"; return; }; int main() { int l1[] = {9, 9, 9}; int l2[] = {1, 8}; int size1 = sizeof(l1) / sizeof(l1[0]); int size2 = sizeof(l2) / sizeof(l2[0]); node* head1 = NULL, *head2 = NULL, *result = NULL; int i; for (int i = size1 - 1; i >= 0; --i) push(&head1, l1[i]); for (int i = size2 - 1; i >= 0; --i) push(&head2, l2[i]); addList(head1, head2, &result); printList(result); return 0; }
相关文章推荐
- 把两个链表加起来 add two numbers represented by two linked lists
- Add two numbers represented by linked lists | Set 2
- 【小熊刷题】Add Two Numbers in Linked Lists
- 【12】Adds two numbers represented by a linked list and returns the sum as a linked list
- leetcode 2. Add Two Numbers (linked lists)
- LeetCode Compare Version Numbers, Maximum Gap, Find Peak Element, Intersection of Two Linked Lists
- LinkedList-445-Add Two Numbers II
- Linked List -- Leetcode problem 2. Add Two Numbers
- LinkedList-2-Add Two Numbers
- [LeetCode BY Python]160. Intersection of Two Linked Lists
- [CrackCode] 2.4 Add two numbers and return the sum as a linked list
- 2. Add Two Numbers(Linked List)
- 【算法世界】(九)LeetCode -- Add Two Numbers by ListNode
- (LinkedList)2. Add Two Numbers
- 【Leetcode】Add Two Numbers (2 lists)
- 【Leetcode】Add Two Numbers
- [LeetCode] Add Two Numbers
- [LeetCode]#2 Add Two Numbers
- [LeetCode][Java] Add Two Numbers
- 明明的leetcode日常:2. Add Two Numbers