题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here if (head1 == null || head2 == null) return null; if (head1 != null && head2 == null) return head1; if (head1 == null && head2 != null) return head2; //逆序 ListNode lnHead1 = new ListNode(0); while (head1 != null) { ListNode lnTmp = lnHead1.next; lnHead1.next = head1; ListNode lnTmpSec = head1.next; head1.next = lnTmp; head1 = lnTmpSec; } ListNode lnHead2 = new ListNode(0); while (head2 != null) { ListNode lnTmp = lnHead2.next; lnHead2.next = head2; ListNode lnTmpSec = head2.next; head2.next = lnTmp; head2 = lnTmpSec; } lnHead1 = lnHead1.next; lnHead2 = lnHead2.next; int nC = 0; ListNode lsRtn = new ListNode(0); while (lnHead1 != null && lnHead2 != null) { int nRtn = (nC + lnHead1.val + lnHead2.val) % 10; nC = (nC + lnHead1.val + lnHead2.val) / 10; ListNode lsRtnC = new ListNode(nRtn); ListNode lnTmp = lsRtn.next; lsRtn.next = lsRtnC; lsRtnC.next = lnTmp; lnHead1 = lnHead1.next; lnHead2 = lnHead2.next; } while (lnHead1 != null) { int nRtn = (nC + lnHead1.val) % 10; nC = (nC + lnHead1.val) / 10; ListNode lsRtnC = new ListNode(nRtn); ListNode lnTmp = lsRtn.next; lsRtn.next = lsRtnC; lsRtnC.next = lnTmp; lnHead1 = lnHead1.next; } while (lnHead2 != null) { int nRtn = (nC + lnHead2.val) % 10; nC = (nC + lnHead2.val) / 10; ListNode lsRtnC = new ListNode(nRtn); ListNode lnTmp = lsRtn.next; lsRtn.next = lsRtnC; lsRtnC.next = lnTmp; lnHead2 = lnHead2.next; } if (nC > 0) { ListNode lsRtnC = new ListNode(nC); ListNode lnTmp = lsRtn.next; lsRtn.next = lsRtnC; lsRtnC.next = lnTmp; } return lsRtn.next; } }