题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { private ListNode reverse(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { Stack<ListNode> stack1 = new Stack<>(); Stack<ListNode> stack2 = new Stack<>(); while (head1 != null) { stack1.push(head1); head1 = head1.next; } while (head2 != null) { stack2.push(head2); head2 = head2.next; } ListNode result = new ListNode(0); ListNode curr = result; int sum = 0; while (!stack1.isEmpty() || !stack2.isEmpty()) { if (!stack1.isEmpty()) { sum += stack1.pop().val; } if (!stack2.isEmpty()) { sum += stack2.pop().val; } curr.next = new ListNode(sum % 10); curr = curr.next; sum = sum >= 10 ? 1 : 0; } // 这里容易忘记 if (sum > 0) { curr.next = new ListNode(sum); } return reverse(result.next); } }