BM11 链表相加(二)

发布于:2025-07-10 ⋅ 阅读:(25) ⋅ 点赞:(0)

目录

题目链接

题目

解题思路

代码


题目链接

链表相加(二)_牛客题霸_牛客网

题目

解题思路

先将两个链表翻转,然后创建一个新的哑结点,开始while连接计算,最后将除哑结点之后的节点翻转即可

代码
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if(head1==null) return head2;
        if(head2==null) return head1;
        head1= reverseLinkedList(head1);
        head2= reverseLinkedList(head2);
        ListNode dummyNode=new ListNode(-1);
        ListNode cur=dummyNode;
        int val=0;
        while(head1!=null||head2!=null){
            if(head1!=null){
                val+=head1.val;
            }
            if(head2!=null){
                val+=head2.val;
            }
            if(head1!=null){
                head1.val=val%10;
                cur.next=head1;
            }else{
                head2.val=val%10;
                cur.next=head2;
            }
            cur=cur.next;
            if(head1!=null) head1=head1.next;
            if(head2!=null) head2=head2.next;
            val=val/10;
        }
        if(val!=0){
            cur.next=new ListNode(val);
        }
        dummyNode=dummyNode.next;
        dummyNode= reverseLinkedList(dummyNode);
        return dummyNode;
    }
    public ListNode reverseLinkedList(ListNode head){
        ListNode pre,cur;
        pre=null;
        while(head!=null){
            cur=head.next;
            head.next=pre;
            pre=head;
            head=cur;
        }
        return pre;
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到