LC-2:两数相加
题目要求:
我的算法代码:(有问题)
public class AtomicDemone { public static void main(String[] args) { ListNode node1 = new ListNode(2); ListNode node2 = new ListNode(4); ListNode node3 = new ListNode(3); node1.next = node2; node2.next = node3; ListNode node4 = new ListNode(5); ListNode node5 = new ListNode(6); ListNode node6 = new ListNode(4); node4.next = node5; node5.next = node6; ListNode listNode = addTwoNumbers(node1, node4); while (listNode != null) { System.out.println(listNode.val); listNode = listNode.next; } } public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ArrayList<Integer> list = new ArrayList<>(); ListNode result = new ListNode(-1); int flag = 0; // 标志位,进位标志 // 对两个链表进行共同遍历 while (l1 != null && l2 != null) { int temp = l1.val + l2.val; if (temp > 9) { // 需要进位 int num1 = temp % 10; // 个位数 int num2 = temp / 10; // 十位数 list.add(num1); flag = num2; //记录下来 } else { // 不需要进位,直接添加到ArrayList中 list.add(temp + flag); } l1 = l1.next; l2 = l2.next; } // 对l1链表进行剩余遍历 while (l1 != null) { int temp = l1.val + flag; if (temp > 9) { int num1 = temp % 10; // 个位数 int num2 = temp / 10; // 十位数 list.add(num1); flag = num2; //记录下来 } else { list.add(temp + flag); } l1 = l1.next; } // 对l2链表进行剩余遍历 while (l2 != null) { int temp = l2.val + flag; if (temp > 9) { int num1 = temp % 10; // 个位数 int num2 = temp / 10; // 十位数 list.add(num1); flag = num2; //记录下来 } else { list.add(temp + flag); } l2 = l2.next; } // 将链表中的元素进行遍历,对每一个元素进行创建新的结点,形成链表进行返回。 ListNode current = result; for (int i = 0; i < list.size(); i++) { ListNode temp = new ListNode(list.get(i)); current.next = temp; current = current.next; } return result.next; } }
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { int next1 = 0; int total = 0; ListNode dummy = new ListNode(-1); ListNode cur = dummy; while (l1 != null && l2 != null) { total = l1.val + l2.val + next1; cur.next = new ListNode(total % 10); next1 = total / 10; l1 = l1.next; l2 = l2.next; cur = cur.next; } while (l1 != null) { total = l1.val + next1; cur.next = new ListNode(total % 10); next1 = total / 10; l1 = l1.next; cur = cur.next; } while (l2 != null) { total = l2.val + next1; cur.next = new ListNode(total % 10); next1 = total / 10; l2 = l2.next; cur = cur.next; } if (next1 != 0) { cur.next = new ListNode(next1); } return dummy.next; }