image.png

解法一: 反转链表相加法

思路:先将两个链表进行反转,然后对应的值进行相加后生成新的链表,最后将链表再进行反转即得到结果!

  1. import java.util.*;
  2. public class Solution {
  3. public ListNode addInList (ListNode head1, ListNode head2) {
  4. head1 = reverse(head1);
  5. head2 = reverse(head2);
  6. ListNode newNode = new ListNode(-1);
  7. ListNode tmp = newNode;
  8. int add = 0;
  9. while(head1 != null || head2 != null){
  10. int val = add;
  11. if(head1 != null){
  12. val+=head1.val;
  13. head1 = head1.next;
  14. }
  15. if(head2 != null){
  16. val+=head2.val;
  17. head2 = head2.next;
  18. }
  19. tmp.next = new ListNode(val%10);
  20. add = val/10;
  21. tmp = tmp.next;
  22. }
  23. if(add > 0)
  24. tmp.next = new ListNode(add);
  25. return reverse(newNode.next);
  26. }
  27. public ListNode reverse(ListNode head){
  28. if(head == null) return head;
  29. ListNode tail = head;
  30. head = head.next;
  31. tail.next = null;
  32. while(head != null){
  33. ListNode temp = head.next;
  34. head.next = tail;
  35. tail = head;
  36. head = temp;
  37. }
  38. return tail;
  39. }
  40. }

解法二:利用栈+头插法

思路: 利用栈先进先出的性质,分别将两个链表中从头往后遍历出所有的值存进去两个栈中,然后再分别从两个栈的栈顶取元素进行相加,有进位则保留,每次插入到链表的头部,最后要进行一次特判,判断此时的进位是否大于0,若大于0则需要将最后的这个进位插进去。

  1. import java.util.*;
  2. public class Solution {
  3. public ListNode addInList (ListNode head1, ListNode head2) {
  4. if(head1 == null) return head2;
  5. if(head2 == null) return head1;
  6. Stack<Integer> stack1 = initStack(head1);
  7. Stack<Integer> stack2 = initStack(head2);
  8. return initListNode(stack1,stack2);
  9. }
  10. public Stack initStack(ListNode head){
  11. Stack<Integer> stack = new Stack<>();
  12. while(head!=null){
  13. stack.add(head.val);
  14. head = head.next;
  15. }
  16. return stack;
  17. }
  18. public ListNode initListNode(Stack<Integer> stack1, Stack<Integer> stack2){
  19. ListNode head = null;
  20. int add = 0;
  21. while(!stack1.isEmpty() || !stack2.isEmpty()){
  22. int val1 = !stack1.isEmpty()?stack1.pop():0;
  23. int val2 = !stack2.isEmpty()?stack2.pop():0;
  24. int val = (val1+val2+add)%10;
  25. add = (val1+val2+add)/10;
  26. ListNode node = new ListNode(val);
  27. if(head == null){
  28. head = node;
  29. }else{
  30. node.next = head;
  31. head = node;
  32. }
  33. }
  34. if(add > 0){
  35. ListNode node = new ListNode(add);
  36. node.next = head;
  37. head = node;
  38. }
  39. return head;
  40. }
  41. }