题解 | 链表相加(二)
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*; public class Solution { public ListNode addInList (ListNode head1, ListNode head2) { // write code here // 需要设置一个进位,查看是否需要进位,将进位后的结果(对10取模)加入新的链表节点 if(head1 == null) return head2; if(head2 == null) return head1; head1 = ReverseList(head1); head2 = ReverseList(head2); ListNode res = new ListNode(-1); ListNode head = res; int carry = 0; // 只要某个链表还有或者进位还有 while(head1 != null || head2 != null || carry != 0){ int val1 = head1 == null ? 0 : head1.val; int val2 = head2 == null ? 0 : head2.val; int temp = val1 + val2 + carry; // 获取进位 carry = temp / 10; temp %= 10; head.next = new ListNode(temp); head = head.next; if(head1 != null){ head1 = head1.next; } if(head2 != null){ head2 = head2.next; } } return ReverseList(res.next); } //反转链表 public ListNode ReverseList(ListNode pHead) { if (pHead == null) return null; ListNode cur = pHead; ListNode pre = null; while (cur != null) { //断开链表,要记录后续一个 ListNode temp = cur.next; //当前的next指向前一个 cur.next = pre; //前一个更新为当前 pre = cur; //当前更新为刚刚记录的后一个 cur = temp; } return pre; } }