栈
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) { Stack<Integer> num1 = new Stack<>(); Stack<Integer> num2 = new Stack<>(); for(ListNode i = head1; i!=null;i=i.next) num1.push(i.val); for(ListNode i = head2; i!=null;i=i.next) num2.push(i.val); int add1 = 0; int count = 0; ListNode sumhead = new ListNode(0); while(!num1.empty() || !num2.empty() || add1 ==1){ int dig1 = num1.empty()?0:num1.pop(); int dig2 = num2.empty()?0:num2.pop(); int cursum = dig1 + dig2 + add1; ListNode temp = new ListNode(cursum%10); temp.next = sumhead.next; sumhead.next = temp; if(dig1 + dig2 + add1 >9) add1 = 1; else add1 = 0; } return sumhead.next; } }
反转链表
注意最后一位 都为空的时候 也有可能得到后面数组的进位。所以也要判断一下
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) { head1 = reverseList(head1); head2 = reverseList(head2); ListNode sumhead = new ListNode(0); int ifadd = 0; while(head1!=null || head2!=null){ ListNode temp = sumhead.next; int res; if(head1 == null){ res = head2.val + ifadd; }else if(head2 == null){ res = head1.val + ifadd; }else{ res = head1.val + head2.val + ifadd; } if(res >= 10){ res = res%10; ifadd = 1; } else{ ifadd = 0;} sumhead.next = new ListNode(res); sumhead.next.next = temp; if(head1!=null) head1 = head1.next; if(head2!=null) head2 = head2.next; } if(ifadd == 1){ ListNode temp = sumhead.next; sumhead.next = new ListNode(1); sumhead.next.next = temp; } return sumhead.next; } public ListNode reverseList(ListNode head){ ListNode cur = head; ListNode prev = null; while(cur!=null){ ListNode temp = cur.next; cur.next = prev; prev = cur; cur = temp; } return prev; } }