题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { if (head1 == null) return head2; if (head2 == null) return head1; // 根据题目要求,先反转链表 ListNode new1 = reverseList(head1); ListNode new2 = reverseList(head2); // 链表相加 int cnt = 0; // 表示是否有进位 int temp = 0; ListNode p1 = new1; ListNode p2 = new2; while (p1.next != null && p2.next != null) { temp = p1.val + p2.val + cnt; p1.val = p2.val = temp % 10; cnt = temp / 10; p1 = p1.next; p2 = p2.next; } temp = p1.val + p2.val + cnt; p1.val = p2.val = temp % 10; cnt = temp / 10; boolean flag = p2.next == null; // 判断谁最长 false 表示 p2长 while (p1.next != null) { if (cnt == 0) break; p1 = p1.next; temp = p1.val + cnt; p1.val = temp % 10; cnt = temp / 10; } while (p2.next != null) { if (cnt == 0) break; p2 = p2.next; temp = p2.val + cnt; p2.val = temp % 10; cnt = temp / 10; } if (cnt != 0) { if (flag) { // 表示p1 为最终结果 p1.next = new ListNode(cnt); return reverseList(new1); } else { p2.next = new ListNode(cnt); return reverseList(new2); } } else { if (flag) return reverseList(new1); return reverseList(new2); } } // 链表反转——头插法 private ListNode reverseList(ListNode head) { if (head == null) return null; ListNode pre = null; ListNode newHead = head; ListNode next; while (newHead != null) { next = newHead.next; newHead.next = pre; pre = newHead; newHead = next; } return pre; } }
代码行数有点多,但量不多。主要还是思路比较简单,所以写的判断就有点小多。采用的计算方法也是比较繁琐的,不知道哪位大佬有更加简便的方法,欢迎评论。
#我的实习求职记录#