namespace Test2; // Definition for singly-linked list. public class ListNode { public int val; public ListNode next; public ListNode(int val=0, ListNode next=null) { this.val = val; this.next = next; } } public class Solution3 { private ListNode CreateListNodeByArr(int[] arr,int index) { if(index == arr.Length - 1) return null; var root = new ListNode(arr[index]); root.next = CreateListNodeByArr(arr, index + 1); return root; } public void Show() { int[] arr1 = {9,9,9,9,9,9,9}; int[] arr2 = {9,9,9,9}; // var l1 = CreateListNodeByArr(arr1,0); // var l2 = CreateListNodeByArr(arr2,0); // 链表构造的方法。。。。。。。 ListNode l1 = new ListNode(9); ListNode l1Cur = l1; foreach(var item in arr1) { l1Cur.next = new ListNode(item); l1Cur = l1Cur.next; } l1 = l1.next; ListNode l2 = new ListNode(9); ListNode l2Cur = l2; foreach(var item in arr2) { l2Cur.next = new ListNode(item); l2Cur = l2Cur.next; } l2 = l2.next; // l1.next = new ListNode(9); // l1.next.next = new ListNode(3); // ListNode l2 = new ListNode(5); // l2.next = new ListNode(6); // l2.next.next = new ListNode(4); var rt = AddTwoNumbers(l1, l2); Console.WriteLine(rt.val); } public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { // 递推 ListNode pre = new ListNode(); ListNode cur = pre; // 这里的没看懂,这里使用就不会改变pre的值。 var carry = (l1.val + l2.val) / 10; while(l1 != null || l2 != null || carry != 0) { var x = l1 == null ? 0 : l1.val; var y = l2 == null ? 0 : l2.val; var val = (x + y + carry) % 10; cur.next = new ListNode(val); cur = cur.next; carry = (x + y + carry) / 10; l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } return pre.next; } }
标签:ListNode,val,next,力扣,l2,l1,new,两数 From: https://www.cnblogs.com/Insist-Y/p/17288793.html