first commit
This commit is contained in:
commit
f86bd9c3d6
2 changed files with 89 additions and 0 deletions
86
main.go
Normal file
86
main.go
Normal file
|
@ -0,0 +1,86 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type ListNode struct {
|
||||
Val int
|
||||
Next *ListNode
|
||||
}
|
||||
|
||||
func (l *ListNode) Add(val int) {
|
||||
newNode := &ListNode{Val: val}
|
||||
current := l
|
||||
for current.Next != nil {
|
||||
current = current.Next
|
||||
}
|
||||
current.Next = newNode
|
||||
}
|
||||
func (l *ListNode) Get(index int) (int, error) {
|
||||
current := l
|
||||
for i := 0; i < index; i++ {
|
||||
if current.Next != nil {
|
||||
current = current.Next
|
||||
} else {
|
||||
return 0, errors.New("there is nothing to index at")
|
||||
}
|
||||
|
||||
}
|
||||
return current.Val, nil
|
||||
}
|
||||
func (l *ListNode) GetNr() int {
|
||||
res := 0
|
||||
multiplyer := 1
|
||||
current := l
|
||||
for current.Next != nil {
|
||||
res = res + (current.Val * multiplyer)
|
||||
multiplyer = multiplyer * 10
|
||||
current = current.Next
|
||||
}
|
||||
res = res + (current.Val * multiplyer)
|
||||
return res
|
||||
}
|
||||
func (l *ListNode) Length() int {
|
||||
count := 0
|
||||
if l.Val != 0 {
|
||||
count++
|
||||
}
|
||||
current := l
|
||||
for current.Next != nil {
|
||||
current = current.Next
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
|
||||
s2 := strconv.Itoa(l1.GetNr() + l2.GetNr())
|
||||
a := []rune(s2)
|
||||
head := &ListNode{Val: 0}
|
||||
res := head
|
||||
|
||||
for _, r := range a {
|
||||
nr, err := strconv.Atoi(string(r))
|
||||
if err != nil {
|
||||
panic("lol")
|
||||
}
|
||||
res.Next = &ListNode{Val: nr}
|
||||
res = res.Next
|
||||
|
||||
}
|
||||
return head.Next
|
||||
}
|
||||
|
||||
func main() {
|
||||
l1 := ListNode{Val: 2}
|
||||
l1.Add(4)
|
||||
l1.Add(3)
|
||||
l2 := ListNode{Val: 5}
|
||||
l2.Add(6)
|
||||
l2.Add(4)
|
||||
l3 := addTwoNumbers(&l1, &l2)
|
||||
fmt.Println(l3.GetNr())
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue