leetcode 2 Add Two Numbers golang

来源:互联网 发布:巴黎散步道 知乎 编辑:程序博客网 时间:2024/06/10 06:25

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解题思路:

先把两个连表放在slice中,对两个slice进行相加进位放在新的slice中,再把slice连接成连表。
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {    sl1 := make([] int ,0,4) //存第一个连表的slice    sl2 := make([] int ,0,4) //存第二个连表的slice    temp1 := l1 //第一个连表的指针    temp2 := l2     //循环吧第一个连表放进slice    for {         sl1 = append(sl1,temp1.Val)           if(temp1.Next == nil ){            break        }            temp1 = temp1.Next    }    for {         sl2 = append(sl2,temp2.Val)         if(temp2.Next == nil ){            break        }        temp2 = temp2.Next    }    s := make([]ListNode ,0,5) //最终存放的连表    len1 := len(sl1)    len2 := len(sl2)    var big [] int    var small [] int  // 找到比较长的连表    if len1 > len2 {        big = sl1        small = sl2    }else{        big = sl2        small = sl1    }    x := 0      //把两个slice的值相加     for i , bigValue := range big{        var smallValue int  //长度小的slice没有了就加 0         if i < len(small){            smallValue = small[i]        }else{            smallValue = 0        }       bigValue = bigValue + x + smallValue //每次加上进位的值       realValue := bigValue % 10       x = bigValue / 10       s = append(s,ListNode{realValue,nil}) //放在要返回的slice中    }     if x != 0 {        s = append(s,ListNode{x,nil}) //最后相加进了一位    }    cnt := len(s)    //连接成连表    for i := cnt - 2 ; i >= 0 ;i--{        s[i].Next = &s[i + 1]    }    return  &s[0]}
1 0
原创粉丝点击