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
Solution1: Do not allocate extra space, but change the value in the original lists.
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} */public class Solution {public ListNode addtwonumbers (listnode L1, ListNode L2) {if (l1==n Ull&&l2==null) return null; if (l1==null) return L2; if (l2==null) return L1; ListNode ptr1 = L1, ptr2 = L2; int c = 0; ListNode Prev=l1;//reserve The previous value in the generated list while (Ptr1!=null && ptr2!=null) { Ptr1.val = Ptr1.val+ptr2.val+c; c = PTR1.VAL/10; Ptr1.val = ptr1.val%10; prev = PTR1; Ptr1=ptr1.next; Ptr2=ptr2.next; } if (ptr2!=null) {//ptr1==null prev.next = ptr2; PTR1 = PTR2; Ptr2=null; Must do the maintaining end condition} while (C!=0&&ptr1!=null) {ptr1.Val =ptr1.val+c; c = PTR1.VAL/10; Ptr1.val = ptr1.val%10; prev = PTR1; PTR1 = Ptr1.next; } if (c!=0&&ptr1==null&&ptr2==null) {ListNode newNode =new listnode (1); Prev.next = NewNode; PTR1 = NewNode; } return L1; }}
Solution 2: Does not change the value in the original lists. But a new list needs to be created
* public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} */public class Solution {public ListNode addtwonumbers (listnode L1, ListNode L2) {if (l1==n Ull&&l2==null) return null; if (l1==null) return L2; if (l2==null) return L1; ListNode head = new ListNode (0); int c = 0; ListNode Prev=head;//reserve The previous value in the generated list while (L1!=null | | l2!=null) {LISTN Ode cur = new ListNode (0); if (l1!=null) {cur.val + = L1.val; L1=l1.next; } if (L2!=null) {cur.val + = L2.val; L2=l2.next; } Cur.val + = C; c = CUR.VAL/10; Cur.val = cur.val%10; Prev.next = cur; prev = cur; } if (c!=0) {ListNode newNode =new listnode (1); Prev.next = NewNode; } return head.next; }}
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Article 13 title Add Numbers