leetcode刷题之旅(2)Add Two Numbers

题目描述

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
Explanation: 342 + 465 = 807.


思路分析

题意即,两链表节点分别相加,考虑两链表不为空的情况下,处理进位情况,分别相加即可,其余见注释。


代码

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode sentinel = new ListNode(0);//创建新链表
		ListNode d = sentinel;
		int sum = 0;
		while (l1!=null || l2!=null)
		{
			sum /=10;   //sum依次与进位,l1,l2相加
			if (l1 != null) 
			{
				sum += l1.val; 
				l1 = l1.next;
			}
			if (l2 != null)
			{
				sum += l2.val; 
				l2 = l2.next;
			}
			d.next = new ListNode(sum % 10);  //d的下一节点为两数之和,注意%是保证个位数
			d = d.next;  //删除d节点,用d.next替代
		}
		if (sum/10 == 1)//考虑最后两位和大于10的情况
		{
			d.next = new ListNode(1);  //因为无后续节点,不用删除了
		}
		return sentinel.next;
	}



猜你喜欢

转载自blog.csdn.net/sun10081/article/details/80177285