leetcode 2 Add Two Numbers
2016-04-06 12:56
309 查看
问题
https://leetcode.com/problems/add-two-numbers/代码(36ms)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int over = 0; int add = 0; ListNode * head = new ListNode(0); ListNode * now = head; while(l1||l2){ if (l1 && l2) { add = l1->val + l2->val + over; l1 = l1->next; l2= l2->next; } else{ if (l1) { add = l1->val + over; l1 = l1->next; }else// l2; { add = l2->val + over; l2 = l2->next; } } over = add / 10; add = add %10; now->next = new ListNode(add); // 指向 下一个位置。。 now = now->next; } if (over) { now->next = new ListNode(over); } if (head->next != NULL)// 说明result链表有长度, { now = head; head = head->next; delete now; } return head; } };
为方便链表建立,为头指针指向一个无用的节点,最后删除这个无用节点。
注意每次写完一个节点,要将当前指针后移。
$(".MathJax").remove();
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解