概述
定义节点
public classListNode {
public intval;
publicListNode next;
public ListNode(intx){
this.val =x;
}
}
两数相加
public class AddTwoNums {
public static void main(String[] args){
ListNode l1 = new ListNode(5);
ListNode l2 = new ListNode(5);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
l2.next.next.next = new ListNode(1);
l2.next.next.next.next = new ListNode(2);
print(l1);
print(l2);
AddTwoNums addTwoNums = new AddTwoNums();
print(addTwoNums.addTwoNumbers(l1,l2));
}
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode targetList = new ListNode(0);
ListNode p = l1;
ListNode q = l2;
ListNode current = targetList;
while(p != null || q != null){
int x = 0,y = 0,sum;
if (p != null) {
x = p.val;
p = p.next;
}
if (q != null) {
y = q.val;
q = q.next;
}
sum = x+y+current.val;
int carry = sum/10;
int reminder = sum%10;
current.val = reminder;
current.next = new ListNode(carry);
current = current.next;
}
current = targetList;
while (current.next.next != null){
current = current.next;
}
if (current.next.val == 0)
current.next = null;
return targetList;
}
/**
* 遍历list
* @param listNode
* @return
*/
public static ListNode print(ListNode listNode){
if (listNode != null) {
System.out.print(listNode.val +"->");
return print(listNode.next);
}
else{
System.out.println("NULL");
return null;
}
}
}
最后
以上就是欣喜凉面为你收集整理的java实现两个链表的数相加,两数相加 Java链表实现的全部内容,希望文章能够帮你解决java实现两个链表的数相加,两数相加 Java链表实现所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复