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->5and5->9->2, return8->0->8.
解題思路及代碼見閱讀原文
回復0000查看更多題目
解題思路
首先,該題的難度為中等,但是通過率還是很高的,相信很多同學都能做出來。思路也較為簡單,每個節(jié)點相加,注意進位。唯一需要注意的是細節(jié),保證無bug。
第一個細節(jié)是,這里不需要沒計算一次就生成一個新節(jié)點,使用鏈表中的節(jié)點效率更高。
第二個細節(jié)是最高位的進位,即當最高位有進位時,要生成一個新節(jié)點插入鏈表結尾。
注意了上述細節(jié)后應該就沒有太大問題了,下面我們來看代碼。
代碼如下
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;
}
}
關注我
該公眾號會每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學有所幫助
image