Java怎么返回首节点

50次阅读
没有评论

共计 1417 个字符,预计需要花费 4 分钟才能阅读完成。

本篇内容主要讲解“Java 怎么返回首节点”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让丸趣 TV 小编来带大家学习“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 怎么返回首节点”有了更深的了解,不妨来实际操作一番吧!这里是丸趣 TV 网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-16发表,共计1417字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)