我是靠谱客的博主 大意豆芽,最近开发中收集的这篇文章主要介绍java实现两个链表相加返回一个新的链表,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目描述
给定两个非空链表来表示两个非负整数,位数按照逆序方式存储,它们的节点只存储单个数字,将两数相加返回一个新的链表。


public class demo1 {
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
ListNode l2 = new ListNode(5);
l1.next = new ListNode(4);
l2.next = new ListNode(6);
System.out.println(ListNode.print(addTwoNumbers(l1,l2)));
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
public static
String print(ListNode l){
StringBuilder sb = new StringBuilder();
while(l != null){
sb.append(l.val);
l=l.next;
}
return sb.toString();
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
while(l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
//进位取余
cur.next = new ListNode(sum);
cur = cur.next;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if(carry == 1) {
cur.next = new ListNode(carry);
}
return pre.next;
}
}

最后

以上就是大意豆芽为你收集整理的java实现两个链表相加返回一个新的链表的全部内容,希望文章能够帮你解决java实现两个链表相加返回一个新的链表所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部