LeetCode 2


### Description:

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.

  • 题意:
    输入两个链表代表两个整数, 输出一个链表代表两个整数和

  • 思路:
    根据竖式整数相加顺序遍历即可, 具体看代码



Example:


  1. Input:  (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output:  7 -> 0 -> 8
    Explanation:  342 + 465 = 807.


代码


Golang

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	// 头结点
	var head *ListNode
	// 遍历节点
	r := &ListNode{}
	head = r
	// 进位
	var jw int = 0
	for {
		e := &ListNode{}
		r.Val, jw = (l1.Val+l2.Val+jw)%10, (l1.Val+l2.Val+jw)/10
		if l1.Next == nil && l2.Next == nil && jw == 0 {
			break
		}
		r.Next = e
		r = r.Next
		if l1.Next != nil {
			l1 = l1.Next
		} else {
			l1.Val = 0
		}
		if l2.Next != nil {
			l2 = l2.Next
		} else {
			l2.Val = 0
		}
	}
	return head
}

posted @ 2018-03-12 20:15  shengwudiyi  阅读(102)  评论(0编辑  收藏  举报