您好,登錄后才能下訂單哦!
本篇內容主要講解“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怎么返回首節點”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。