Java怎么返回首节点

发布时间:2021-12-20 13:45:34 作者:iii
来源:亿速云 阅读:200

本篇内容主要讲解“Java怎么返回首节点”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java怎么返回首节点”吧!

You are given two linked lists representing two non-negative numbers.    
The digits are stored in reverse order and each of their nodes contain a single digit.    
Add the two numbers and return it as a linked list.      
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class AddTwoNumbers {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l1n1 = new ListNode(4);
        ListNode l1n2 = new ListNode(3);

        ListNode l2 = new ListNode(5);
        ListNode l2n1 = new ListNode(6);
        ListNode l2n2 = new ListNode(4);

        l1.next = l1n1;
        l1n1.next = l1n2;

        l2.next = l2n1;
        l2n1.next = l2n2;

        AddTwoNumbers atn = new AddTwoNumbers();
        ListNode pre = atn.addTwoNumbers(l1,l2);
        Utils.print(pre);
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry =0;

        ListNode newHead = new ListNode(0);//作为暂存首节点
        ListNode p1 = l1, p2 = l2, p3=newHead; //p3作为操作变量

        while(p1 != null || p2 != null){
            if(p1 != null){
                carry += p1.val;
                p1 = p1.next;
            }

            if(p2 != null){
                carry += p2.val;
                p2 = p2.next;
            }

            p3.next = new ListNode(carry%10);
            p3 = p3.next;
            carry /= 10;
        }

        if(carry==1)
            p3.next=new ListNode(1);

        return newHead.next; //返回首节点
    }
}

到此,相信大家对“Java怎么返回首节点”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. jQuery层级选择器_动力节点节点Java学院整理
  2. jQuery动画_动力节点节点Java学院整理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java怎么输出两个数字

下一篇:SPSS如何合并文件并添加个案

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》