GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/code/lc2.java at master · mJackie/leetcode Expand file tree/ Copy pathlc2.javaMore file actions 41 lines (39 loc) · 1.17 KB / Copy pathlc2.javaFile metadata and controls41 lines (39 loc) · 1.17 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 package code; /* * 2. Add Two Numbers * 题意:两个链表,节点上的数逆序组成一个数字,求和,返回链表 * 难度:Medium * 分类:Linked List, Math * 算法:两个链表一起遍历,按位加,注意进位 * Tips:不要遍历完一个链表保存为变量,求变量和再转化为链表。因为链表可能很长,变量无法保存下来; * 注意考虑两个链表长度不一致的问题 */ public class lc2 { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum = 0; ListNode result = new ListNode(0); ListNode cur = result; while(l1!=null || l2!=null){ if(l1!=null) { sum += l1.val; l1 = l1.next; } if(l2!=null) { sum += l2.val; l2 = l2.next; } cur.next = new ListNode(sum%10); cur = cur.next; sum = sum/10; } if(sum==1) { cur.next = new ListNode(1); } return result.next; } public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |