/** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here Stack<Integer> stack1 = new Stack(); Stack<Integer> stack2 = new Stack(); while(head1 != null){ stack1.push(head1.val); head1 = head1.next; } while(head2 != null){ stack2.push(head2.val); head2 = head2.next; } int n = 0; int n1 = 0; int n2 = 0; int ca = 0; ListNode pre = null; ListNode node = null; while(!stack1.isEmpty() || !stack2.isEmpty()){ n1 = stack1.isEmpty()?0:stack1.pop(); n2 = stack2.isEmpty()?0:stack2.pop(); n = n1 + n2 +ca; pre = node; node = new ListNode(n%10); node.next = pre; ca = n/10; } if(ca == 1){ pre = node; node = new ListNode(1); node.next = pre; } return node; }
标签:node,pre,ListNode,head2,head1,求和,相加,链表,stack2 From: https://www.cnblogs.com/shijianchuzhenzhi/p/16808472.html