[LeetCode] Add Two Numbers

要注意迭代是每次向前走一步的,所以設置一個head表示答案前面的一個node,類似鏈表的頭節點。

用一個引用從head開始向後迭代,l1、l2就直接指向下一個就可以,後面也不用了。用carry記錄有無進位。

迭代完成後檢查有沒有進位,有就多加一個1,最後不要head,返回head的下一個node。

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
		ListNode cur = head;
		int carry = 0;
		while(l1 != null || l2 != null) {
			int n1 = (l1!=null? l1.val: 0);
			int n2 = (l2!=null? l2.val: 0);
			int sum = n1+n2+carry;
			carry = (sum>=10? 1: 0);
			cur.next = new ListNode(sum % 10);
			cur = cur.next;
			if(l1 != null) {
				l1 = l1.next;
			}
			if(l2 != null) {
				l2 = l2.next;
			}
		}
		if(carry == 1) {
			cur.next = new ListNode(1);
		}
		return head.next;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章