leetCode第二题答案,两个链表存储形式的数据加和,最终返回一个链表(java版分析)

题目详情

leetCode第二题答案,两个链表存储形式的数据加和,最终返回一个链表(java版分析)_第1张图片

我的开始代码解析

这个代码是简单实现版,没有追求代码的精简。

package com.ke.leetCodes;


class ListNode {
    int val;
     ListNode next;
     ListNode(int x) { val = x; }
  }
 
//Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
//Output: 7 -> 0 -> 8
//Explanation: 342 + 465 = 807.

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	if(l1==null) return l2;
    	if(l2==null) return l1;
    	ListNode t1 = l1;
    	ListNode t2 = l2;
    	ListNode result = null;
    	ListNode head = null;
    	int carry = 0;
    	int data = 0;
    	while(t1!=null&&t2!=null){
    		data = (t1.val+t2.val+carry)%10;  
    		carry = (t1.val+t2.val+carry)/10; //进位
    		ListNode current = new ListNode(data);
    		
    		if(result == null) {
    			result = current;
    			head = result;
    		}else{
    			result.next = current;
    			result = result.next;
    		}
    		t1 = t1.next;
    		t2 = t2.next;
    	}
    	while(t1!=null){
    		data = (t1.val+carry)%10;  
    		carry = (t1.val+carry)/10; //进位
    		ListNode current = new ListNode(data);
    		if(result == null) {
    			result = current;
    			head = result;
    		}else{
    			result.next = current;
    			result = result.next;
    		}
    		t1 = t1.next;
    	}
    	while(t2!=null){
    		data = (t2.val+carry)%10;  
    		carry = (t2.val+carry)/10; //进位
    		ListNode current = new ListNode(data);
    		if(result == null) {
    			result = current;
    			head = result;
    		}else{
    			result.next = current;
    			result = result.next;
    		}
    		t2 = t2.next;
    	}
    	if(carry!=0){
    		ListNode current = new ListNode(carry);
    		result.next = current;
			result = result.next;
    	}
    	
    	
    	return head;
        
    }
    
  //Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  //Output: 7 -> 0 -> 8
  //Explanation: 342 + 465 = 807.
    public static void main(String[] args) {
//		int [] a1 = new int[]{2,4,3};
//		int [] a2 = new int[]{5,6,4};
		int [] a1 = new int[]{1};
		int [] a2 = new int[]{9,9};
		ListNode l1 = null;
		ListNode l2 = null;
		ListNode h1 = null;
		ListNode h2 = null;
		for(int i = 0;i

精选答案

如果不看别的大神写的代码,永远都不会提高:
答案。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

可以从参考答案中借鉴的点

  1. 将表头直接新建了个值为0的节点,这样保证头结点是可以直接next,而不抛空指针异常。
  2. 循环语句的精简:既然都是一遍大循环,为什么循环不能用在一个里面呢?
  3. 最后的进位,仍然要进行判断,如果有进位,要再新加一个节点,进行链接。

你可能感兴趣的:(LeetCode,Datastruct,面试)