您的位置:首页 > 其它

leetcode题解-2. Add Two Numbers

2017-12-10 14:03 423 查看
题意:给你两个表示两个非负数字的链表。数字以相反的顺序存储,其节点包含单个数字。将这两个数字相加并将其作为一个链表返回。

例子:输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)

输出: 7 -> 0 -> 8

解释:342 + 465 = 807.

分析:这道题比较简单,两个链表相加的问题,思路很明确,就是按照位数读下去,维护当前位和进位,时间复杂度是O(n),空间复杂度是O(1).

另外本题是链表部分的第一题,所以也附上链表部分的主函数和打印函数,以后的链表部分题目为了简介不在包含主函数。值得注意的是,因为本题定义了链表节点的数据结构,因此包含Solution.java和ListNode.java两部分的代码。以后为了精简博客,ListNode.java部分的代码也不再附上。

Solution.java

class Solution {
public  ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) return null;
ListNode point = new ListNode(0);
ListNode head = point;
int carry = 0;
while(l1 != null && l2 != null){
int sum = carry + l1.val + l2.val;
point.next = new ListNode(sum % 10);
point = point.next;
carry = sum /10;
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null){
int sum = carry + l1.val;
point.next = new ListNode(sum % 10);
point = point.next;
carry = sum /10;
l1 = l1.next;
}
while(l2 != null){
int sum = carry + l2.val;
point.next = new ListNode(sum % 10);
point = point.next;
carry = sum /10;
l2 = l2.next;
}
if(carry != 0){
point.next = new ListNode(carry);
}

return head.next;
}
public static void print(ListNode head){
while(head != null){
System.out.println(head.val);
head = head.next;
}

}
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
ListNode l2 = new ListNode(4);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(5);
ListNode l5 = new ListNode(6);
ListNode l6 = new ListNode(4);
l1.next = l2;
l2.next = l3;
l4.next = l5;
l5.next = l6;
print(addTwoNumbers(l1, l4));

}
}


ListNode.java

// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: