LeetCode【2】. Add Two Numbers--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(in x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode slist = new ListNode(0); ListNode clist = slist; ListNode nlist = new ListNode(0); //int sval = 0; int flag = 0; // 进位 //1. if First Node of l1 or l2 is null if(l1==null||l2==null){ return (l1==null)?((l2==null)?(slist):(l2)):(l1); } //2.1 当l1,l2都非链尾时,loop while(true) { clist.val = (l1.val + l2.val + flag)%(10); flag = (l1.val + l2.val + flag)/10; //next node l1 = l1.next; l2 = l2.next; //2.1.1 若任意一个为链尾,则跳出 if(l1==null||l2==null){ break; }else{ clist.next= new ListNode(0); clist =clist.next; } };//while //2.2 如果两个同时为链尾时 if(l1==null&&l2==null) { //2.2.1 若两个为链尾且有进位,结果需进位 if(flag==1){ nlist = new ListNode(flag); clist.next = nlist; }else{ return slist; } }else //2.2 一个到达链尾、一个还未 { ListNode onelist = new ListNode(0); if(l1==null) {onelist = l2; }else {onelist = l1; } while(onelist!= null) { clist.next = new ListNode(0); clist = clist.next; clist.val = (onelist.val + flag)%10; flag = (onelist.val + flag)/10; onelist = onelist.next; } //2.2.1 当另外一个也到达链尾,判断是否有进位 if(flag==1) { clist.next = new ListNode(flag); } } return slist; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。