Golang算法 - Leetcode

 主页   资讯   文章   代码   电子书 

2. Add Two Numbers

Leetcode 链接

题目

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题意解析

两个数分别用两个链表倒序表示,要求将两个链表相加,相加结果同样用链表表示并且返回该链表。

解决方案

对两个链表同时进行遍历即可。

Go 代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    head := &ListNode{
        Val: 0,
        Next: nil,
    }

    current := head
    last := 0

    for l1 != nil || l2 != nil{
        val := last
        if l1 != nil {
            val += l1.Val
            l1 = l1.Next
        }

        if l2 != nil {
            val += l2.Val
            l2 = l2.Next
        }

        current.Next = &ListNode{
            Val: val%10,
            Next: nil,
        }
        last = val/10
        current = current.Next
    }

    if last != 0 {
        current.Next = &ListNode{
            Val: last,
            Next: nil,
        }
    }

    return head.Next
}