题目:
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
思路:
没有要求时间空间复杂度,单纯链表操作。而且给出了Node的定义。建一个临时的head,指向第一个Node,根据加法算出后面的Node。再返回head.next即可。注意一些特殊情况以免漏掉一些case。
代码:(有点冗余,但是勉强ac了)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode temp = head;
int flag = 0;
while(l1!=null&&l2!=null){
if((l1.val+l2.val+flag)>9){
temp.next = new ListNode(l1.val+l2.val-10+flag);
temp = temp.next;
flag = 1;
}else {
temp.next = new ListNode(l1.val+l2.val+flag);
temp = temp.next;
flag = 0;
}
l1 = l1.next;
l2 = l2.next;
}
while(l1!=null){
if((l1.val+flag)>9){
temp.next = new ListNode(l1.val+flag-10);
temp = temp.next;
flag = 1;
}
else{
temp.next = new ListNode(l1.val+flag);
temp = temp.next;
flag = 0;
}
l1 = l1.next;
}
while(l2 !=null){
if((l2.val+flag)>9){
temp.next = new ListNode(l2.val+flag-10);
temp = temp.next;
flag = 1;
}
else{
temp.next = new ListNode(l2.val+flag);
temp = temp.next;
flag = 0;
}
l2 = l2.next;
}
if(flag == 1){
temp.next = new ListNode(1);
}
return head.next;
}
}
网友评论