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)
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
问题分析:题目的意思是要每位按照位来求和,超过10向下面一位进1,自身对10取余数。想到的最直接的解法是讲新的结果保存到一个新的链表中。每次循环注意求得进位和余数就可以了。实现代码如下:
/**
* 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 *p=l1,*q=l2,*head=NULL,*m=NULL;
if(p==NULL) return q;
if(q==NULL) return p;
if(p==NULL&&q==NULL) return NULL;
int count=0;
while (p || q) {
int num1=0,num2=0;
if(p!=NULL) num1=p->val;
if(q!=NULL) num2=q->val;
int sum=num1+num2+count;
cout<<sum<<endl;
count = sum / 10;
int val = sum % 10;
ListNode* cur = new ListNode(val);
if (!head) {
head=cur;
}
if(m){
m->next=cur;
}
m=cur;
p = p? p->next: NULL;
q = q? q->next: NULL;
}
if (count > 0) {
ListNode* l = new ListNode(count);
m->next = l;
}
return head;
}
然后,虽然ac了,还是不甘心,140ms,发现这样的实现算法中新建很多节点相当的耗时。于是想到另外一种解法,就是利用原来的二个链表,理解的关键就是当你选中作为开头的那个链表遍历完了但是另外一个还没有遍历完,这个如何让后序元素连接起来,于是这里多加了一个指针来记录那种情况发生的时候,选中的链表的结尾,其他思想和上面差不多,要注意最后一步count是否为0,不为零的话需要新增加一个节点来保存该值。这下时间成为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) {
ListNode *p=l1,*q=l2,*head=NULL,*m=NULL;
if(p==NULL) return q;
if(q==NULL) return p;
if(p==NULL&&q==NULL) return NULL;
int count=0;
while(p&&q){
int num1=0,num2=0;
if(p) num1=p->val;
if(q) num2=q->val;
int sum=num1+num2+count;
count=sum/10;
int yusu=sum%10;
p->val=yusu;
m=p;
p=(p->next==NULL)?NULL:p->next;
q=(q->next==NULL)?NULL:q->next;
}
if(q!=NULL){
m->next=q;
p=q;
}
while(p){
int num1=0;
if(p!=NULL) num1=p->val;
int sum=num1+count;
count=sum/10;
int yusu=sum%10;
p->val=yusu;
m=p;
p=(p->next==NULL)?NULL:p->next;
}
if (count > 0) {
ListNode* l = new ListNode(count);
m->next = l;
}
return l1;
}
};