2.5 Sum Lists

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
Input: (7-> 1 -> 6) + (5 -> 9 -> 2) . That is, 617 + 295.
Output: 2 -> 1 -> 9. That is, 912.
FOLLOW UP
Suppose the digits are stored in forward order. Repeat the above problem.
Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295.
Output: 9 -> 1 -> 2. That is, 912.

Hint
  • Of course, you could convert the linked lists to integers, compute the sum, and then convert it back to a new linked list. If you did this in an interview, your interviewer would likely accept the answer, and then see if you could do this without converting it to a number and back.
  • Try recursion. Suppose you have two lists, A = 1 -> 5 -> 9 (representing 951) and B = 2 - > 3 - >6 - > 7 (representing 7632), and a function that operates on the remainder of the lists (5 - >9 and 3 -> 6 - > 7). Could you use this to create the sum method? What is the relationship between sum(1 -> 5 -> 9, 2 -> 3 -> 6 -> 7) and sum(5 -> 9, 3 -> 6 -> 7)?
  • Make sure you have considered linked lists that are not the same length.
  • Does your algorithm work on linked lists like 9 -> 7 -> 8 and 6 -> 8 -> 5? Double check that.
  • For the follow-up question: The issue is that when the linked lists aren't the same length, the head of one linked list might represent the 1000's place while the other represents the 10's place. What if you made them the same length? Is there a way to modify the linked list to do that, without changing the value it represents?
Solution

由于鏈表已經(jīng)是從低位到高位排列,因此只需要從左至右遍歷兩鏈表取出對應(yīng)位累加肮韧,同時(shí)記錄下進(jìn)位信息即可锄弱,下面是迭代的寫法

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(-1), curNode = dummyHead;
    int carry = 0;
    while (l1 != null || l2 != null) {
        int v1 = l1 == null ? 0 : l1.val;
        int v2 = l2 == null ? 0 : l2.val;
        int sum = v1 + v2 + carry;
        carry = sum / 10;
        curNode.next = new ListNode(sum % 10);
        curNode = curNode.next;
        if (l1 != null) l1 = l1.next;
        if (l2 != null) l2 = l2.next;
    }
    if (carry == 1) curNode.next = new ListNode(1);
    return dummyHead.next;
}

此外蚤蔓,還可以通過遞歸來寫

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    if (l1 == null) return l2;
    else if (l2 == null) return l1;

    int sum = l1.val + l2.val;
    ListNode node = new ListNode(sum % 10);
    node.next = addTwoNumbers(l1.next, l2.next);
    if (sum >= 10) node.next = addTwoNumbers(node.next, new ListNode(1));
    return node;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市利朵,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖陆淀,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異先嬉,居然都是意外死亡倔约,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進(jìn)店門坝初,熙熙樓的掌柜王于貴愁眉苦臉地迎上來浸剩,“玉大人,你說我怎么就攤上這事鳄袍【钜” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵拗小,是天一觀的道長重罪。 經(jīng)常有香客問我,道長哀九,這世上最難降的妖魔是什么剿配? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮阅束,結(jié)果婚禮上呼胚,老公的妹妹穿的比我還像新娘。我一直安慰自己息裸,他們只是感情好蝇更,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著呼盆,像睡著了一般年扩。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上访圃,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天厨幻,我揣著相機(jī)與錄音,去河邊找鬼。 笑死况脆,一個(gè)胖子當(dāng)著我的面吹牛平绩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播漠另,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼捏雌,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了笆搓?” 一聲冷哼從身側(cè)響起性湿,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎满败,沒想到半個(gè)月后肤频,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡算墨,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年宵荒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片净嘀。...
    茶點(diǎn)故事閱讀 39,834評論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡报咳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出挖藏,到底是詐尸還是另有隱情暑刃,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布膜眠,位于F島的核電站岩臣,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏宵膨。R本人自食惡果不足惜架谎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望辟躏。 院中可真熱鬧谷扣,春花似錦、人聲如沸鸿脓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽野哭。三九已至,卻和暖如春幻件,著一層夾襖步出監(jiān)牢的瞬間拨黔,已是汗流浹背绰沥。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工篱蝇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人零截。 一個(gè)月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像涧衙,于是被迫代替她去往敵國和親哪工。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評論 2 354

推薦閱讀更多精彩內(nèi)容