Skip to content

Instantly share code, notes, and snippets.

@rtsoy
Created January 1, 2026 14:12
Show Gist options
  • Select an option

  • Save rtsoy/437cbcdf8d680edbf71b6eb7b098bf4a to your computer and use it in GitHub Desktop.

Select an option

Save rtsoy/437cbcdf8d680edbf71b6eb7b098bf4a to your computer and use it in GitHub Desktop.
2. Add Two Numbers
// 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