您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“Java怎么返回首節(jié)點(diǎn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Java怎么返回首節(jié)點(diǎn)”吧!
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);//作為暫存首節(jié)點(diǎn) 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; //返回首節(jié)點(diǎn) } }
到此,相信大家對“Java怎么返回首節(jié)點(diǎn)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。