题解 | #链表相加(二)# Stack + 暴力
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here Stack<Integer> stk1 = new Stack<>(); Stack<Integer> stk2 = new Stack<>(); //Stack<Integer> result = new Stack<>(); while(head1!=null){ stk1.push(head1.val); head1 = head1.next; } while(head2!=null){ stk2.push(head2.val); head2 = head2.next; } int maxLen = Math.max(stk1.size(), stk2.size()); int result[] = new int[maxLen + 1]; for(int i = 0; i < maxLen; i++){ int a = stk1.isEmpty()?0:stk1.pop(); int b = stk2.isEmpty()?0:stk2.pop(); int sum = a + b + result[i]; if(sum >= 10) { result[i] = sum - 10; result[i+1] = 1; }else{ result[i] = sum; } } int hasPrefix = 0; ListNode vNode = new ListNode(-1); ListNode cur = new ListNode(-1); vNode.next = cur; for(int i=maxLen;i>=0;i--){ System.out.print(result[i]); if(hasPrefix == 0 && result[i] == 0){ continue; }else if(hasPrefix == 0 && result[i] != 0){ cur.next = new ListNode(result[i]); cur = cur.next; hasPrefix = 1; }else{ cur.next = new ListNode(result[i]); cur = cur.next; } } return vNode.next.next; } }
善用数据结构的一些特性,尤其是对于链表,栈的使用是非常常见的。