题目大意:给定两个数,以两个链表的形式给出,算出他们的和,最后返回一个新链表。
解题思路:把给定的两个链表逆序,求和,在把求出的和即为所求的链表。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; int flag = 0; ListNode res = new ListNode(0); ListNode tmp = new ListNode(0); res = tmp; l1 = reverse(l1); l2 = reverse(l2); while(l1 != null || l2 != null){ int a = l1 == null?0:l1.val; int b = l2 == null?0:l2.val; ListNode ss = new ListNode((a+b+flag)%10); flag = (a+b+flag) /10; tmp.next = ss; tmp = ss; l1 = l1 == null? null:l1.next; l2 = l2 == null? null:l2.next; } if(flag == 1){ ListNode ss = new ListNode(1); tmp.next = ss; } return reverse(res.next); } public ListNode reverse(ListNode l1){ if(l1.next == null) return l1; ListNode p = new ListNode(0); ListNode q = new ListNode(0); p = l1; q = l1.next; p.next = null; while(q != null){ p = q; q = q.next; p.next = l1; l1 = p; } return l1; } }