题目
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
解题思路
1. 主要的单链表操作,注意最后的进位。时间复杂度O(max|m,n|)。空间复杂度O(max|m,n|)。(√)
代码
/** * 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) { ListNode head=null,tail=null; int first=1; int sum; int flag=0; while(l1!=null || l2!=null){ sum=flag; if(l1!=null && l2!=null){sum+=l1.val+l2.val;l1=l1.next;l2=l2.next;} else if(l1!=null){sum+=l1.val;l1=l1.next;} else {sum+=l2.val;l2=l2.next;} flag=sum/10; ListNode node = new ListNode(sum%10); if(first==1){ first=0; head=node; tail=node; }else{ tail.next=node; tail=node; } } if(flag!=0){ ListNode node = new ListNode(flag); tail.next=node; } return head; } }
执行结果