题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
这道题目难点在于存储数字的顺序是反过来的,于是我们借助于反转链表的思想
- 首先将两个链表反转
- 然后利用反转之后的链表来计算求得每个节点的值
- 将得到的新链表反转,得到结果
// 反转链表 func reverseList(head *ListNode) *ListNode { if head == nil { return nil } var pre *ListNode cur := head next := head.Next for cur != nil && cur.Next != nil { cur.Next = pre pre = cur cur = next next = next.Next } cur.Next = pre return cur }
然后
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { newList := &ListNode{} newHead := newList //进位值 mod := 0 for l1 != nil || l2 != nil || mod != 0 { val1,val2 := 0,0 if l1 != nil { val1 = l1.Val } if l2 != nil { val2 = l2.Val } //当前的数 val := (val1 + val2 + mod) % 10 //是否进位 mod = (val1 + val2 + mod) / 10 newList.Next = &ListNode{ Val:val, } newList = newList.Next if l1 != nil { l1 = l1.Next } if l2 != nil { l2 = l2.Next } } return newHead.Next }