Created
January 1, 2026 14:12
-
-
Save rtsoy/437cbcdf8d680edbf71b6eb7b098bf4a to your computer and use it in GitHub Desktop.
2. Add Two Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/add-two-numbers/ | |
| // | |
| // Time: O(N) | |
| // Space: O(N) | |
| // | |
| // N = number of nodes in the longer list | |
| // .................... // | |
| /** | |
| * Definition for singly-linked list. | |
| * type ListNode struct { | |
| * Val int | |
| * Next *ListNode | |
| * } | |
| */ | |
| func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { | |
| head := &ListNode{} | |
| node := head | |
| sum := 0 | |
| for l1 != nil || l2 != nil || sum > 0 { | |
| if l1 != nil { | |
| sum += l1.Val | |
| l1 = l1.Next | |
| } | |
| if l2 != nil { | |
| sum += l2.Val | |
| l2 = l2.Next | |
| } | |
| node.Next = &ListNode{Val: sum % 10} | |
| node = node.Next | |
| sum /= 10 | |
| } | |
| return head.Next | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment