题目:
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
两个非空链表代表分别代表一个整数,高位存在链表尾,低位存在链表头,相加后的结果存在链表里。
思路:
从链表头开始相加即可,设置进位符,结果一边计算一边存入新链表。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
int jw,add;
jw=0;
ListNode tail,p,q;//res为结果链表指针,tail为结果的链尾指针
ListNode res=new ListNode(-1);
tail=res;
p=l1;
q=l2;
while(p!=null&&q!=null){
add=p.val+q.val+jw;
jw=add/10;
add=add%10;
ListNode newnode=new ListNode(add);
tail.next=newnode;
tail=tail.next;
p=p.next;
q=q.next;
}
if(p==null){
while(q!=null){
add=q.val+jw;
jw=add/10;
add=add%10;
ListNode newnode=new ListNode(add);
tail.next=newnode;
tail=tail.next;
q=q.next;
}
}
else if(q==null){
while(p!=null){
add=p.val+jw;
jw=add/10;
add=add%10;
ListNode newnode=new ListNode(add);
tail.next=newnode;
tail=tail.next;
p=p.next;
}
}
if(jw!=0){
ListNode newnode=new ListNode(jw);
tail.next=newnode;
}
return res.next;
}
}
注意两个链表长度不一的情况,注意最后两个链表都遍历完但是有还有进位的情况。
类似题目: