【Leetcode】445. Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
Tips:给定两个单链表,将两个单链表中的值相加。
思路:链表都是按照从前到后连接的,而整数加法需要从低位开始相加,即链表的后面开始相加。
我才用两个list来保存链表的val,按照从后向前的顺序相加,并将结果保存在一个list中。最后将list按照从后向前的顺序,赋值给一个新的链表。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); while (l1 != null) { list1.add(l1.val); l1 = l1.next; } while (l2 != null) { list2.add(l2.val); l2 = l2.next; } int len1 = list1.size(); int len2 = list2.size(); //将较长的链表保存在list1中 if (len1 < len2) { List<Integer> temp = list2; list2 = list1; list1 = temp; } int len = len1 > len2 ? len1 : len2;// 最后链表的长度为len或者len+1 System.out.println(len); List<Integer> list = new ArrayList<>(); int diff = Math.abs(len1 - len2); int tag = 0; //从后向前进行整数加法。 for (int i = len - 1; i >= 0; i--) { //如果两个链表长度不相等,保证右对齐 ,先将能对其的位置相加.剩下的位置只加list1即可 int temp = tag + list1.get(i); if (i - diff >= 0) { temp += list2.get(i - diff); } if (temp >= 10) { //进1 tag = 1; temp -= 10; } else { tag = 0; } list.add(temp); } if (tag > 0) list.add(1); //打印list中的值 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } ListNode head = new ListNode(-1); ListNode node = new ListNode(0); head.next = node; //将list从后向前 赋值给链表结点 for (int i = list.size() - 1; i >= 0; i--) { node.next = new ListNode(list.get(i)); node = node.next; } node.next = null; return head.next.next; }
测试代码:
public static void main(String[] args) { ListNode node1 = new ListNode(7); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(4); ListNode node4 = new ListNode(3); node1.next = node2; node2.next = node3; node3.next = node4; ListNode nu = null; node4.next = nu; ListNode node11 = new ListNode(5); ListNode node21 = new ListNode(6); ListNode node31 = new ListNode(4); node11.next = node21; node21.next = node31; ListNode nu1 = null; node31.next = nu1; L445AddTwoNumbersII l445 = new L445AddTwoNumbersII(); ListNode head = l445.addTwoNumbers(node11, node1); while (head != null) { System.out.println("~~~~~~~~~~~~"); System.out.println(head.val); head = head.next; }
}