Skip to content

Commit

Permalink
两个链表中的数字相加
Browse files Browse the repository at this point in the history
  • Loading branch information
cdtft committed May 14, 2020
1 parent e7ddf20 commit 203aab6
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/main/java/com/cdtft/leetcode/Solution.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.cdtft.leetcode;

import org.w3c.dom.NodeList;

import javax.xml.soap.Node;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
Expand Down Expand Up @@ -555,4 +557,68 @@ public int[] intersection(int[] nums1, int[] nums2) {
return result;
}

private boolean flag = false;

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
LinkedList<Integer> stack1 = new LinkedList<>();
LinkedList<Integer> stack2 = new LinkedList<>();
while (l1 != null) {
stack1.offer(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.offer(l2.val);
l2 = l2.next;
}
LinkedList<Integer> result = new LinkedList<>();
while (!stack1.isEmpty() && !stack2.isEmpty()) {
Integer num1 = stack1.poll();
Integer num2 = stack2.poll();
Integer sum = num1 + num2;
offerResult(sum, result);
}
pollList(stack1, result);
pollList(stack2, result);
ListNode node = null;
while (!result.isEmpty()) {
if (node == null) {
node = new ListNode(result.poll());
} else {
ListNode temp = node;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new ListNode(result.poll());
}
}
if (flag) {
ListNode temp = node;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new ListNode(1);
}
return node;
}

private void pollList(LinkedList<Integer> list, LinkedList<Integer> result) {
while (!list.isEmpty()) {
Integer sum = result.poll();
offerResult(sum, result);
}
}

private void offerResult(Integer sum, LinkedList<Integer> result) {
if (flag) {
sum += 1;
flag = false;
}
if (sum > 9) {
result.offer(sum % 10);
flag = true;
} else {
result.offer(sum);
}
}

}
7 changes: 7 additions & 0 deletions src/test/java/com/cdtft/leetcode/SolutionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,11 @@ public void removeElements() {
public void containsNearbyDuplicate() {
solution.containsNearbyDuplicate(new int[]{1, 2, 3, 1, 2, 3}, 2);
}

@Test
public void addTwoNumbers() {
ListNode node1 = new ListNode(0);
ListNode node2 = new ListNode(7, new ListNode(3));
solution.addTwoNumbers(node1, node2);
}
}

0 comments on commit 203aab6

Please sign in to comment.