LeetCode algorithm 2. Add two numbers

Algorithm: Add two numbers

Two non-empty linked lists are given to represent two non-negative integers. Among them, their respective digits are stored in reverse order, and each node can only store one digit.

If we add these two numbers together, a new linked list will be returned to represent their sum.
You can assume that except for the number 0, neither of these numbers will start with 0.
Insert picture description here
Let's first understand the ListNode data type. ListNode is a linked list object in java defined by itself

class ListNode {
    
            //类名 :Java类就是一种自定义的数据结构
    int val;            //数据 :当前节点数据 
    ListNode next;      //对象 :引用下一个节点对象。在Java中没有指针的概念,Java中的引用和C语言的指针类似
    
    ListNode(int val){
    
      //构造方法 :构造方法和类名相同   
        this.val=val;     //把接收的参数赋值给当前类的val变量
    }
}

Note: Each node has a val value

Question ideas:
1. First judge whether the two linked lists are empty at the same time, if they are empty, no more calculations are performed and return directly.
2. Set a head node and carry value addOne when it is not empty.
3. Add the first node of the two ListNodes, %10 takes the remaining number as the single digit value, and /10 takes the integer as the carry value, and the head pointer moves backward to point to the single digit value.
4. The head pointer continues to move backward to point to the next bit. When l1 and l2 are not empty, it also continues to move backward and execute the loop.
5. The calculation stops when both l1 and l2 are empty and addOne is 0.
6. Return dummy.next refers to the pointer of the first position of the linked list, so that the linked list can be looked up later

        public  ListNode addTwoNumbers(ListNode l1,ListNode l2){
    
    
            //判断l1,l2是否同时为空
            if(l1 == null && l2 ==null){
    
    
                return null;
            }
            //定义进一位的变量addOne,初始为0
            int addOne = 0;
            //定义头指针
            ListNode dummy = new ListNode(0);
            ListNode head = dummy;
            //循环遍历条件l1不为null,l2不为null,addOne为0
            while (l1 != null || l2 != null || addOne !=0){
    
    
                //取末尾元素的值
               int val1 = l1 == null ? 0 : l1.val;
               int val2 = l2 == null ? 0 : l2.val;
               //相加
               int sum = val1 + val2 + addOne;
               //取余,确定相加首位置的值
               head.next = new ListNode(sum % 10);
               //head指针后移
               head = head.next;
               //取整,确定进位值
               addOne = sum / 10;
               // l1、l2指针后移
               if(l1 != null) l1 = l1.next;
               if(l2 != null) l2 = l2.next;
            }
            return dummy.next;
        }

Note: The dummy is set to record the value of the current node, and the head is to move the pointer backward.
The test process is as follows:

    public static class ListNode {
    
    
        int val;
        ListNode next;

        public ListNode(int x) {
    
    
            val = x;
        }

        public static String print(ListNode l) {
    
    
            StringBuilder sb = new StringBuilder();
            while (l != null) {
    
    
                sb.append(l.val);
                l = l.next;
            }
            return sb.toString();
        }
    }
    public static void main(String[] args) {
    
    
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(5);
        l1.next = new ListNode(4);
        l2.next = new ListNode(6);
        System.out.println(ListNode.print(addTwoNumbers(l1,l2)));


    }

Note: Dummy is the head node whose value is empty. The next node of dummy is the newly created linked list and the first position, which is the ListNode type (pointer). Then the pointer that knows the first position can continue to traverse the table and output the result. The process is as follows The above code.

Guess you like

Origin blog.csdn.net/weixin_46801232/article/details/108664124