两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。给出两个链表 3->1->5->null
和 5->9->2->null
,返回 8->0->8->null.....
下面就是我的程序
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *head;
ListNode *p1 = new ListNode; //必须分配地址
int carry=0,carry1;
head=p1;
if (l1==NULL)
return l2;
if(l2==NULL)
return l1;
while(l1!=NULL && l2!=NULL){
p1->val=l1->val+l2->val+carry;
carry=(p1->val)/10;
carry1=(p1->val)%10;
if(carry==1){
p1->val=carry1;
}
l1=l1->next;
l2=l2->next;
if(l1!=NULL && l2!=NULL){
p1->next = new ListNode; //必须分配地址
p1=p1->next;
}
}
if(l1==NULL){
while(l2!=NULL){
p1->next = new ListNode; //dddddd
p1=p1->next;
p1->val=l2->val+carry;
carry=(p1->val)/10;
carry1=(p1->val)%10;
if(carry==1)
p1->val=carry1;
l2=l2->next;
}
}
if(l2==NULL){
while(l1!=NULL){
p1->next = new ListNode; //ddddd
p1=p1->next;
p1->val=l1->val+carry;
carry=(p1->val)/10;
carry1=(p1->val)%10;
if(carry==1)
p1->val=carry1;
l1=l1->next;
}
}
if(carry==1){ //最后一个数看是不是大于10,
p1->next = new ListNode;
p1=p1->next;
p1->val=1;
p1->next=NULL;
}
else{
p1->next=NULL;
}
return head;
}
};
运行得出结果,