Skip to content

Commit

Permalink
Add new linked list exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Jan 5, 2024
1 parent dbb68b9 commit fea9f19
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
41 changes: 41 additions & 0 deletions golang/2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package golang

/**
* Definition for singly-linked list.
* type ListNode2 struct {
* Val int
* Next *ListNode2
* }
*/

type ListNode2 struct {
Val int
Next *ListNode2
}

func addTwoNumbers(l1 *ListNode2, l2 *ListNode2) *ListNode2 {
carry := 0
head := &ListNode2{Val: 0}
current := head

for l1 != nil || l2 != nil || carry > 0 {
total := carry

if l1 != nil {
total += l1.Val
l1 = l1.Next
}

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

carry = total / 10
(*current).Next = &ListNode2{Val: total % 10}
current = current.Next
}

return head.Next

}
36 changes: 36 additions & 0 deletions golang/2_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package golang

import "testing"
import "slices"

func TestFirstAddTwoNumbers(t *testing.T) {

l1 := &ListNode2{
Val: 2,
Next: &ListNode2{
Val: 4,
Next: &ListNode2{Val: 3},
},
}
l2 := &ListNode2{
Val: 5,
Next: &ListNode2{
Val: 6,
Next: &ListNode2{Val: 4},
},
}

result := addTwoNumbers(l1, l2)
s := []int{}

for result != nil {
s = append(s, result.Val)
result = result.Next
}

expected := []int{7, 0, 8}

if !slices.Equal(expected, s) {
t.Fatalf(`Expected %v but received %v`, expected, s)
}
}
1 change: 1 addition & 0 deletions golang/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
| Problem Number | Tag | URL |
| -------------- | ------------------------------ | ------------------------------------------------------------------------------------ |
| 2.go | Linked List | https://leetcode.com/problems/add-two-numbers/ |
| 888.go | Hash table | https://leetcode.com/problems/fair-candy-swap |
| 1290.go | Linked List / Bit manipulation | https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer |
| 1539.go | Binary Search | https://leetcode.com/problems/kth-missing-positive-number/ |
Expand Down

0 comments on commit fea9f19

Please sign in to comment.