力扣hot100 两数相加 链表 思维

Problem: 2. 两数相加
力扣hot100 两数相加 链表 思维_第1张图片

Code

⏰ 时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2)
	{
		ListNode res = new ListNode();
		ListNode cur = res;
		int c = 0;//保存进位信息
		while (l1 != null && l2 != null)//进行两个数最低位的相加
		{
			int x = (l1.val + l2.val + c) % 10;
			cur.next = new ListNode(x);
			cur = cur.next;
			c = (l1.val + l2.val + c) / 10;
			l1 = l1.next;
			l2 = l2.next;
		}
		while (l1 != null)//处理数位较多的数 和 进位
		{
			int x = (l1.val + c) % 10;
			c = (l1.val + c) / 10;
			cur.next = new ListNode(x);
			cur = cur.next;
			l1 = l1.next;
		}
		while (l2 != null)//处理数位较多的数 和 进位
		{
			int x = (l2.val + c) % 10;
			c = (l2.val + c) / 10;
			cur.next = new ListNode(x);
			cur = cur.next;
			l2 = l2.next;
		}
		if (c != 0)//处理最后一个进位
			cur.next = new ListNode(c);

		return res.next;
	}
}

你可能感兴趣的:(力扣,hot100,leetcode,链表,算法)