leetcode 2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
我的思路:把所有的数据往l1上拼接,如果l1比较短,那么就往上面拼接。
/**
* 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) {
ListNode* p1 = l1;
ListNode* p2 = l2;
ListNode* p3 = NULL;
ListNode* p4 = NULL;
int mark = 0;
while (p1 != NULL && p2 != NULL) {
p1->val = p1->val + p2->val;
if (mark) p1->val++, mark = 0;
if (p1->val >= 10) p1->val = p1->val % 10, mark = 1;
p3 = p1;
p1 = p1->next;
p2 = p2->next;
}
if (p2 != NULL) {
while (p2 != NULL) {
ListNode *x = new ListNode(p2->val);
p3->next = x;
if (mark) p3->next->val++, mark = 0;
if (p3->next->val >= 10) p3->next->val = p3->next->val % 10, mark = 1;
p2 = p2->next;
p3 = p3->next;
}
if (mark) {
ListNode *x = new ListNode(1);
p3->next = x;
p3 = p3->next;
}
}
else if (p1 != NULL) {
while (p1 != NULL) {
if (mark) p1->val++, mark = 0;
if (p1->val >= 10) p1->val = p1->val % 10, mark = 1;
p4 = p1;
p1 = p1->next;
}
if (mark) {
ListNode *x = new ListNode(1);
p4->next = x;
p4 = p4->next;
}
}
else {
if (mark) {
ListNode *x = new ListNode(1);
p3->next = x;
p3 = p3->next;
}
}
return l1;
}
};
虽然过了,但是看了别人的代码后感觉自己的代码太长了,差距都是对比出来的
/**
* 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 carry=0;
ListNode* header = new ListNode(0);
ListNode* now = header;
while(l1 || l2 || carry){
now->next = new ListNode(0);
now = now->next;
now->val = (l1?l1->val:0) + (l2?l2->val:0) + carry;
carry = now->val / 10;
now->val = now->val%10;
l1=l1?l1->next:nullptr;
l2=l2?l2->next:nullptr;
}
ListNode* out = header->next;
delete header;
return out;
}
};
今天是开学的第一天,加油。
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: