官方解法
使用栈
链表中的数位的顺序与我们进行相加的顺序是相反的,为了逆序处理所有数位,可以利用栈。
import javax.xml.soap.Node;
//定义链表节点
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
package Day20230703;
//定义链表
public class LinkedList {
ListNode head; // 头节点
LinkedList() {
this.head = null;
}
// 在链表末尾添加新节点,尾插法
void addNode(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
} else {
ListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// 打印链表节点的值
void printList() {
ListNode current = head;
System.out.print("链表节点的值:");
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
}
package Day20230703;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
import java.util.Stack;
import javax.xml.soap.Node;
public class AddTwoNum {
public static void main(String[] args) {
LinkedList l1 = new LinkedList();
LinkedList l2 = new LinkedList();
l1.addNode(7);
l1.addNode(2);
l1.addNode(4);
l1.addNode(3);
l2.addNode(5);
l2.addNode(6);
l2.addNode(4);//这里也可以写while循环来进行创建链表操作
LinkedList l3 = addTwoNum(l1, l2);
l3.printList();
}
public static LinkedList addTwoNum(LinkedList l1,LinkedList l2) {
// Stack<Integer> stack1 = new Stack<Integer>();
// Stack<Integer> stack2 = new Stack<Integer>();
Deque<Integer> s1 = new ArrayDeque<Integer>();
Deque<Integer> s2 = new ArrayDeque<Integer>();
ListNode p = l1.head;
while (p!=null) {
s1.push(p.val);
p=p.next;
}
ListNode q = l2.head;
while (q!=null) {
s2.push(q.val);
q=q.next;
}
int carry = 0;
LinkedList l3 = new LinkedList();
while (!s1.isEmpty()||!s2.isEmpty()||carry!=0) {
int a = s1.isEmpty() ? 0 : s1.pop();
int b = s2.isEmpty() ? 0 : s2.pop();
// if (!s1.isEmpty()) s1.pop();//出栈操作
// if (!s2.isEmpty()) s2.pop();
int cur = a + b + carry;
carry = cur/10;
cur = cur%10;
ListNode newNode = new ListNode(cur);
// if (l3.head==null) {
// l3.head = newNode;
// }
// else {
// newNode.next = l3.head;
// }
newNode.next=l3.head;
l3.head=newNode;
}
return l3;
}
}