2. Add Two Numbers

    xiaoxiao2025-01-20  15

    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

    链表每一位是一个数字位,顺序为又高到底将两条链表的数值相加 返回新的链表

    当两条链表都不为空时,记录这两位数字的和以及上一次运算的进位值,取整  取余 

    public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head=new ListNode(0); head.next=l1; int sum=0;int dig=0;int next=0; if(l1==null&&l2==null)return null; else if(l1==null) return l2; else if(l2==null) return l1; while((l1!=null)&&(l2!=null)){ sum=l1.val+l2.val+next; //记录两位的数位与前一位进位的和 dig=sum%10; //取余是本位的数值 l1.val=dig;<span style="white-space:pre"> </span>//取整是高一位的进位<span style="white-space:pre"> </span> next=sum/10; if(l1.next==null||l2.next==null) //找到链表最后一位。跳出循环,此时已经两条链表不同时为空了 break; l1=l1.next; l2=l2.next; } if(l2.next!=null){ //把l2连到l1 l1.next=l2.next; } while(l1.next!=null){ //继续操作l1 l1=l1.next; sum=l1.val+next; l1.val=sum%10; next=sum/10; } // while(l2.next!=null){ // l1.next=l2.next; // sum=l1.val+next; // l1.val=sum%10; // next=sum/10; // } if(next!=0) { //处理链表的最后一位 如果next不为0 还有进位就要再加上这个点 ListNode last=new ListNode(next); l1.next=last; } return head.next; } }

    转载请注明原文地址: https://ju.6miu.com/read-1295673.html
    最新回复(0)