package com.dengpf.AddTwoNumbers; import org.w3c.dom.ls.LSException; import java.util.ArrayList; import java.util.LinkedList; /** * Created by kobe73er on 16/12/9. * <p> * /** * Definition for singly-linked list. **/ class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode t = new ListNode(0); ListNode l3 = t; ListNode head = t; ListNode tmp = t; // 3->4>6->7 // 3->6>3->0 // 6->0->0->8 int jinwei = 0; while (true) { if (l1 == null && l2 == null) { break; } if (l1 == null) { l1 = new ListNode(0); } if (l2 == null) { l2 = new ListNode(0); } l3.val = l1.val + l2.val + jinwei; if (l3.val >= 10) { jinwei = 1; } else { jinwei = 0; } l3.val %= 10; l3.next = new ListNode(jinwei); l1 = l1.next; l2 = l2.next; l3 = l3.next; } ListNode r = head; if (l3.next == null && l3.val == 0) { int count = 0; while (tmp.next != null) { count++; tmp = tmp.next; } LinkedList<ListNode> tmpList = new LinkedList<ListNode>(); while (count > 0) { ListNode s = new ListNode(head.val); tmpList.add(s); head = head.next; count--; } r = tmpList.get(0); for (int k = 0; k < tmpList.size() - 1; k++) { tmpList.get(k).next = tmpList.get(k + 1); } } return r; } public static void main(String args[]) { ListNode l10 = new ListNode(3); ListNode l11 = new ListNode(4); ListNode l12 = new ListNode(6); ListNode l13 = new ListNode(7); l10.next = l11; l11.next = l12; l12.next = l13; l13.next = null; ListNode l20 = new ListNode(3); ListNode l21 = new ListNode(6); ListNode l22 = new ListNode(3); ListNode l23 = new ListNode(0); // ListNode l21 = new ListNode(7); // ListNode l22 = new ListNode(1); l20.next = l21; l21.next = l22; l22.next = l23; l23.next = null; // // // ListNode l40 = new ListNode(5); // ListNode l50 = new ListNode(5); // // l40.next = null; // l50.next = null; Solution sIns = new Solution(); ListNode head = sIns.addTwoNumbers(l10, l20); // ListNode head = sIns.addTwoNumbers(l40, l50); while (true) { if (head == null) { break; } System.out.print(head.val); head = head.next; } } }
Add two numbers
最新推荐文章于 2021-02-19 08:37:33 发布