【LeetCode practice】2. Add two numbers

【LeetCode practice】2. Add two numbers

2. Add two numbers

Question source link
algorithm idea: linked list;

PS: Java has no pointers; in the linked list, the index of the ListNode that traverses to the end will disappear (such as n1, n2), and it will no longer point to the micro end of the linked list after instantiation! Need to be specially marked, use p.next for instantiation (generation of new linked list nodes)

java code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
    	int nums1 = 0;
    	int nums2 = 0;
    	ListNode res = new ListNode(0);
     	ListNode n1 = l1;//统计l1的长度
    	ListNode n2 = l2;//统计l2的长度
    	while (n1 != null) {
    
    
			nums1++;
			n1 = n1.next;
		}
    	while (n2 != null) {
    
    
			nums2++;
			n2 = n2.next;
		}
    	if(nums1 > nums2) {
    
    //保证l2长度更长
    		ListNode temp = l1;
    		l1 = l2;
    		l2 = temp;
    	}
    	res.next = l2;//运用res.next指向最后答案,方便输出;
    	int index = 0;//进位标志
        while (l1 != null) {
    
    //按照l1长度的进行计算
        	int temp = (l1.val + l2.val + index);//l1+l2数值计算
        	l2.val = temp % 10 ;
			index = temp / 10;
			l1 = l1.next;
			l2 = l2.next;
		}
        while (l2 != null && index == 1) {
    
    //计算l2剩余长度结点的计算
        	int temp = index + l2.val;
        	l2.val = temp % 10;
			index = temp / 10;
			l2 = l2.next;
			
		}
        if(index == 1) {
    
    //判断最后是否有进位
        	ListNode p = res.next;//p指针用来找到最后一个链表结点
            while(p.next != null) {
    
    
            	p = p.next;
            }//找到链表最后一个元素
            p.next = new ListNode(1);//添加进位的数值1
        }
        return res.next;
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/108648771