您的位置:首页 > 其它

LeetCode OJ:Add Two Numbers (相加链表之数)

2015-10-11 17:47 387 查看
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

将两个链表上的数相加就可以,大于10进一位,注意下相加时候的细节就可以了,我这里

吧prev节点记录下来,这样最后多生成节点的时候便于将最后一个多余的节点删除:

/**
* 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 * curr = new ListNode(0);
ListNode * root = curr;
ListNode * prev = curr;
int currVal = 0;
while(l1 != NULL && l2 != NULL){
currVal = l1->val + l2->val;
curr->val += currVal;
curr->next = new ListNode(curr->val/10);
curr->val%=10;
prev = curr;
curr = curr->next;
l1 = l1->next;
l2 = l2->next;
}
while(l1 != NULL){
curr->val += l1->val;
curr->next = new ListNode(curr->val/10);
curr->val %= 10;
prev = curr;
curr = curr->next;
l1 = l1->next;
}
while(l2 != NULL){
curr->val += l2->val;
curr->next = new ListNode(curr->val/10);
curr->val %= 10;
prev = curr;
curr = curr->next;
l2 = l2->next;
}
if(curr->val == 0){
prev->next = NULL;
delete curr;
}
return root;
}
};


感觉写的有点麻烦,应该有很多的重复代码可以改正,但是我暂时找不出来了,先这样吧。

更新下,以前脑子抽了写出了那样的代码。 其实三个while循环都可以放到一个while中, 下面用java在写一起,方法还是类似的:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmp = new ListNode(0);
ListNode head = tmp;
int carry = 0;
while(l1!=null || l2!=null || carry != 0){
int val = ((l1 != null)?l1.val:0) + ((l2!=null)?l2.val:0) + carry;
carry = carry/10 + val/10;
val %= 10;
tmp.next = new ListNode(val);
tmp = tmp.next;
l1 = l1!=null ? l1.next : l1;
l2 = l2!=null ? l2.next : l2;
}
return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: