Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

445. 两数相加 II #76

Open
yankewei opened this issue Nov 23, 2020 · 1 comment
Open

445. 两数相加 II #76

yankewei opened this issue Nov 23, 2020 · 1 comment
Labels
中等 题目难度为中等 链表 题目类型为链表

Comments

@yankewei
Copy link
Owner

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 中等 题目难度为中等 链表 题目类型为链表 labels Nov 23, 2020
@yankewei
Copy link
Owner Author

感觉也没什么说的,就是把链表的元素存到一个数组中,这样可以从数组的尾部向前遍历(栈),然后相加即可。

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var s1 []int
    var s2 []int
    for l1 != nil || l2 != nil {
        if l1 != nil {
            s1 = append(s1, l1.Val)
            l1 = l1.Next
        }
        if l2 != nil {
            s2 = append(s2, l2.Val)
            l2 = l2.Next
        }
    }
    var next *ListNode
    flag := 0
    for len(s1) != 0 || len(s2) != 0 {
        var val1 int
        var val2 int
        if len(s1) != 0 {
            val1 = s1[len(s1)-1]
            s1 = s1[:len(s1)-1]
        }
        if len(s2) != 0 {
            val2 = s2[len(s2)-1]
            s2 = s2[:len(s2)-1]
        }
        val := val1 + val2 + flag
        if (val > 9) {
            val -= 10
            flag = 1
        } else {
            flag = 0
        }
        tNode := &ListNode{Val: val}

        tNode.Next = next
        next = tNode
        
    }
    if flag == 1 {
        return &ListNode{Val: 1, Next: next}
    } else {
        return next
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 链表 题目类型为链表
Projects
None yet
Development

No branches or pull requests

1 participant