题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
一个比较捞的方法。。
求改进
public ListNode addInList (ListNode head1, ListNode head2) { int carry = 0;//进位符 ListNode h1 = reverseList(head1);//链表反转 ListNode h2 = reverseList(head2);//链表反转 //遍历定长部分 ListNode l1 = h1; ListNode l2 = h2; int len1 = 0,len2 = 0; while(l1 != null){ len1++; l1 = l1.next; } while(l2 != null){ len2++; l2 = l2.next; } ListNode ans = new ListNode(-1);//结果链表 if(len1>=len2){ ans.next = head1; }else{ ans.next = head2; }//结果链表定长为较长的一个+1 ListNode f1 = h1; ListNode f2 = h2;//f1和f2双指针用来做加法 ListNode tmp = ans;//创建指针在结果链表上移动 while(f1 != null || f2 != null || carry!=0){ int x=0,y=0; if(f1 != null){ x=f1.val; f1=f1.next; } if(f2 !=null){ y=f2.val; f2=f2.next; } int sum = x+y+carry; tmp.val = sum%10; tmp = tmp.next; carry = sum/10; if(carry==0 && f1 == null && f2==null){ ans = reverseList(ans); //如果全为0,不计算最后一位,反转输出链表.next return ans.next; } } ans = reverseList(ans); return ans; } //链表反转 public ListNode reverseList(ListNode head){ if(head == null || head.next == null){ return head; } Stack<Integer> stack = new Stack<Integer>(); ListNode temp = head; while(temp != null){ stack.push(temp.val); temp = temp.next; } ListNode cur = head; while(!stack.isEmpty()){ cur.val = stack.pop(); cur = cur.next; } return head; }