Update solution 0445

This commit is contained in:
halfrost
2021-09-14 23:47:56 -07:00
parent 5c0f4f9103
commit 7db2a76fd6

View File

@ -32,6 +32,22 @@ Output: 7 -> 8 -> 0 -> 7
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
@ -93,6 +109,75 @@ func getLength(l *ListNode) int {
return count
}
func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
reservedL1 := reverseList(l1)
reservedL2 := reverseList(l2)
dummyHead := &ListNode{}
head := dummyHead
carry := 0
for reservedL1 != nil || reservedL2 != nil || carry > 0 {
val := carry
if reservedL1 != nil {
val = reservedL1.Val + val
reservedL1 = reservedL1.Next
}
if reservedL2 != nil {
val = reservedL2.Val + val
reservedL2 = reservedL2.Next
}
carry = val / 10
head.Next = &ListNode{Val: val % 10}
head = head.Next
}
return reverseList(dummyHead.Next)
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
tmp := head.Next
head.Next = prev
prev = head
head = tmp
}
return prev
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
stack1 := pushStack(l1)
stack2 := pushStack(l2)
dummyHead := &ListNode{}
head := dummyHead
carry := 0
for len(stack1) > 0 || len(stack2) > 0 || carry > 0 {
val := carry
if len(stack1) > 0 {
val = val + stack1[len(stack1)-1]
stack1 = stack1[:len(stack1)-1]
}
if len(stack2) > 0 {
val = val + stack2[len(stack2)-1]
stack2 = stack2[:len(stack2)-1]
}
carry = val / 10
tmp := head.Next
head.Next = &ListNode{Val: val % 10, Next: tmp}
}
return dummyHead.Next
}
func pushStack(l *ListNode) []int {
var stack []int
for l != nil {
stack = append(stack, l.Val)
l = l.Next
}
return stack
}
```