问题:
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
代码:
//
// ad2num.cpp
// Test
//
// Created by mac on 5/19/14.
// Copyright (c) 2014 mac. All rights reserved.
//
#include "ad2num.h"
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *returnL = NULL;
ListNode *haha = returnL;
int tenth = 0;
while(l1 && l2)
{
int temp = l1->val + l2->val + tenth;
tenth = temp/10;
int num = temp%10;
if(!returnL)
{
returnL = new ListNode(num);
haha = returnL;
}
else
{
haha->next = new ListNode(num);
haha = haha->next;
}
l1 = l1->next;
l2 = l2->next;
}
ListNode *lastList = l1?l1:l2;
while(lastList)
{
int temp = lastList->val + tenth;
tenth = temp/10;
int num = temp%10;
if(!returnL)
{
returnL = new ListNode(num);
haha = returnL;
}
else
{
haha->next= new ListNode(num);
haha = haha->next;
}
lastList = lastList->next;
}
if(returnL && tenth)
{
haha->next= new ListNode(tenth);
haha = haha->next;
}
return returnL;
}
};
int main()
{
ListNode *l1 = new ListNode(1);
//l1->next = new ListNode(4);
//l1->next->next = new ListNode(3);
ListNode *l2 = new ListNode(9);
l2->next = new ListNode(9);
l2->next->next = new ListNode(9);
Solution s;
ListNode *result =s.addTwoNumbers(l1 , l2);
while(result)
{
cout<<result->val<<endl;
result = result->next;
}
}
分析:
主要考的内容是链表的掌握。有三个需要注意:
1.链表有可能都是空的,或者某一个为空。
2. 加法有进位,尽管把其中一个链表加到空了,依然得注意到进位,比如 1 + 999 ,显然虽然前面那个队列很快就空了,可留下来的进位不能够丢弃。
3. 最后剩下的链表也不能够简单的链接到新的链表后面,理由和2一样,1+999这种情况,显然把进位带到了最后。
总结:
这个很简单,一次性编译,就成功了,没调试就算对了,通过了网上的检验,数据结构链表部分掌握的还不错。