网上看了诸多大神的代码 然后整合在一起 不知道理解的对不对 有误望指正
ListNode 类
package com.example.mytest.model;
/**
* 自定义ListNode数据结构
*/
public class ListNode {
/**
* 节点数据
*/
public int val;
/**
* 引用下一个节点对象
* 在Java中没有指针的概念,Java中的引用和C语言的指针类似
*/
public ListNode next;
/**
* 有参构造
* @param val
*/
public ListNode(int val) {
this.val = val;
}
}
两数相加
package com.example.mytest.suanfa;
import com.example.mytest.model.ListNode;
import java.util.ArrayList;
import java.util.List;
public class 两数相加 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 链表为空,首节点给0
ListNode xList = new ListNode(0);
// 声明一个变量用来在移动过程中指向当前节点
ListNode newList = xList;
// 定义一个变量,记录相加为10以上的操作,可理解为加法中逢10进1
int curr = 0;
// 以两个链表不为空为条件循环
while (l1 != null || l2 != null) {
//取值,三目判断,val有就取,没有则为0
int x = l1 != null ? l1.val : 0;
int y = l2 != null ? l2.val : 0;
//计算求和
int sum = curr + x + y;
//存值,取整
curr = sum / 10;
//取余先给下一个位置赋值
newList.next = new ListNode(sum % 10);
//移动指针指向下一个值
newList = newList.next;
//取下一个节点的指针
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
// 如果最后相加还能取整,那就接着往后存一位
if (curr > 0) {
newList.next = new ListNode(curr);
}
return xList.next;
}
/**
* 创建链表
* @param listNode
* @param list
* @return
*/
public ListNode createListNode(ListNode listNode, List<Integer> list) {
for (Integer a : list) {
// 创建新节点
ListNode newNode = new ListNode(a);
// 把新节点连接起来
listNode.next = newNode;
// 当前节点往后移动
listNode = listNode.next;
}
return listNode;
}
//打印输出方法
static void print(ListNode listNoed) {
//创建链表节点
while (listNoed != null) {
System.out.println("节点:" + listNoed.val);
listNoed = listNoed.next;
}
System.out.println();
}
/**
* main 测试
* @param args
*/
public static void main(String[] args) {
两数相加 两数相加 = new 两数相加();
ListNode l1 = new ListNode(2);
ListNode l2 = new ListNode(5);
ListNode nextNodeL1;
nextNodeL1 = l1;
ListNode nextNodeL2;
nextNodeL2 = l2;
ArrayList<Integer> listL1 = new ArrayList<>();
ArrayList<Integer> listL2 = new ArrayList<>();
listL1.add(4);
listL1.add(3);
listL2.add(6);
listL2.add(4);
ListNode listNode1 = 两数相加.createListNode(nextNodeL1, listL1);
ListNode listNode2 = 两数相加.createListNode(nextNodeL2, listL2);
nextNodeL1 = l1;
nextNodeL2 = l2;
ListNode listNode = 两数相加.addTwoNumbers(l1, l2);
print(listNode);
}
}
最后输出结果