Add Two Numbers
今天是一道有关链表的题目,来自LeetCode,难度为Medium,Acceptance为21%。
题目如下
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example
Given7->1->6 + 5->9->2
. That is,617 + 295
.
Return2->1->9
. That is912
.
Given3->1->5
and5->9->2
, return8->0->8
.
解题思路及代码见阅读原文
回复0000查看更多题目
解题思路
首先,该题的难度为中等,但是通过率还是很高的,相信很多同学都能做出来。思路也较为简单,每个节点相加,注意进位。唯一需要注意的是细节,保证无bug。
第一个细节是,这里不需要没计算一次就生成一个新节点,使用链表中的节点效率更高。
第二个细节是最高位的进位,即当最高位有进位时,要生成一个新节点插入链表结尾。
注意了上述细节后应该就没有太大问题了,下面我们来看代码。
代码如下
Java版
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists(ListNode l1, ListNode l2) {
// write your code here
if(null == l1)
return l2;
if(null == l2)
return l1;
int carry = 0;
ListNode head = l1, prev = l1;
while(l1 != null && l2 != null) {
prev = l1;
int val = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;
l1.val = val;
l1 = l1.next;
l2 = l2.next;
}
if(l2 != null) {
prev.next = l2;
l1 = l2;
}
while(l1 != null && carry != 0) {
prev = l1;
int val = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
l1.val = val;
l1 = l1.next;
}
if(carry != 0) {
ListNode tail = new ListNode(carry);
prev.next = tail;
}
return head;
}
}
关注我
该公众号会每天推送常见面试题,包括解题思路是代码,希望对找工作的同学有所帮助