Title Description:
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
At the same time traversing two linked lists, summing each node separately, each node only has 1-bit results, preserving the carry for the next node calculation.
Ideas:
1. Two pointers to the first of the list 1 (L1) and linked List 2 (L2), the bitwise calculation can be.
2. After the first node and when the list is traversed, there is a case where the carry is not placed in the list.
/** * Definition for singly-linked list. * public class ListNode {* Public int val, * public ListNode Next, * public ListNode (int x) {val = x;}} */public class Solution {public ListNode addtwonumbers (listnode L1, ListNode L2) { ListNode node = null; ListNode head = null; var carry = 0; while (L1! = NULL | | L2! = NULL) { var a = L1! = null? l1.val:0; var b = L2! = null? l2.val:0; var s = a + B + carry; var r = s%; if (node = = null) { node = new ListNode (r); Head = node; } else{ node.next = new ListNode (r); node = node.next; } carry = S/10; if (L1! = null) { L1 = l1.next; } if (L2! = null) { L2 = L2.next; } } if (Carry > 0) { var n = new ListNode (carry); Node.next = n; } return head; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Add Numbers