main.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. //var l1 = &ListNode{
  7. // 2, &ListNode{4, &ListNode{3, nil}},
  8. //}
  9. //var l2 = &ListNode{
  10. // 5, &ListNode{6, &ListNode{4, nil}},
  11. //}
  12. var l1 = &ListNode{
  13. 9, nil,
  14. }
  15. var l2 *ListNode
  16. var l2Cuosor *ListNode
  17. for i := 0; i < 10; i++ {
  18. if i == 0 {
  19. l2 = &ListNode{1, nil}
  20. l2Cuosor = l2
  21. continue
  22. }
  23. var temp = &ListNode{9, nil}
  24. l2Cuosor.Next = temp
  25. l2Cuosor = l2Cuosor.Next
  26. }
  27. // [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
  28. //[5,6,4]
  29. var result = addTwoNumbers(l1, l2)
  30. listPrint(result)
  31. }
  32. /**
  33. * Definition for singly-linked list.
  34. * type ListNode struct {
  35. * Val int
  36. * Next *ListNode
  37. * }
  38. */
  39. type ListNode struct {
  40. Val int
  41. Next *ListNode
  42. }
  43. func listPrint(list *ListNode) {
  44. for list != nil {
  45. fmt.Printf("%v", list.Val)
  46. if list.Next == nil {
  47. break
  48. }
  49. fmt.Printf(" -> ")
  50. list = list.Next
  51. }
  52. }
  53. func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
  54. var l1Tmp, l2Tmp = l1, l2
  55. var result, resultTemp, lastNode *ListNode
  56. var carry int = 0
  57. for l1Tmp != nil && l2Tmp != nil {
  58. var value = l1Tmp.Val + l2Tmp.Val + carry
  59. tmp := &ListNode{
  60. Val: value % 10,
  61. Next: nil,
  62. }
  63. carry = value / 10
  64. if resultTemp == nil {
  65. resultTemp = tmp
  66. result = resultTemp
  67. } else {
  68. resultTemp.Next = tmp
  69. resultTemp = resultTemp.Next
  70. }
  71. lastNode = l1Tmp.Next
  72. if l1Tmp.Next == nil {
  73. lastNode = l2Tmp.Next
  74. }
  75. l1Tmp = l1Tmp.Next
  76. l2Tmp = l2Tmp.Next
  77. }
  78. for lastNode != nil {
  79. var value = lastNode.Val + carry
  80. var tmp = &ListNode{
  81. Val: value % 10,
  82. Next: nil,
  83. }
  84. carry = value / 10
  85. if resultTemp == nil {
  86. resultTemp = tmp
  87. result = resultTemp
  88. } else {
  89. resultTemp.Next = tmp
  90. resultTemp = resultTemp.Next
  91. }
  92. lastNode = lastNode.Next
  93. }
  94. if carry != 0 {
  95. tmp := &ListNode{Val: carry, Next: nil}
  96. resultTemp.Next = tmp
  97. resultTemp = resultTemp.Next
  98. }
  99. return result
  100. }