链表相加(二)


代码求解

java 复制代码
public ListNode reverseList(ListNode pHead){

		if(pHead == null){
			return null;
		}
		ListNode pre = null;
		ListNode cur = pHead;
		ListNode next = pHead;

		while(cur!=null){
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}

		return pre;
	}
    
    public ListNode addInList (ListNode head1, ListNode head2) {
    // 链表1为空,直接返回链表2
    if (head1 == null) {
        return head2;
    }
    // 链表2为空,直接返回链表1
    if (head2 == null) {
        return head1;
    }

    // 反转两个链表,让低位在前(方便从低位开始相加)
    head1 = reverseList(head1);
    head2 = reverseList(head2);

    ListNode dummy = new ListNode(-1);  // 虚拟头节点:简化结果链表的头节点处理
    ListNode head = dummy;              // 结果链表的当前指针(用于挂载新节点)
    int carry = 0;                      // 进位标志

    // head1未遍历完 || head2未遍历完 || 还有进位(包含carry!=0,处理最后一位相加的进位)
    while (head1 != null || head2 != null || carry != 0) {
        // 获取当前节点的值(链表已遍历完则取0,不影响相加结果)
        int val1 = head1 == null ? 0 : head1.val;
        int val2 = head2 == null ? 0 : head2.val;

        int temp = val1 + val2 + carry;
        carry = temp / 10;  // 更新进位
        temp %= 10;         // 取当前位的结果

        // 创建当前位的节点,挂载到结果链表上
        head.next = new ListNode(temp);
        head = head.next;   // 结果链表指针后移,准备挂载下一个节点

        // 原链表指针后移
        if (head1 != null) {
            head1 = head1.next;
        }
        if (head2 != null) {
            head2 = head2.next;
        }
    }

    // 反转结果链表,恢复高位在前的格式,返回最终结果
    return reverseList(dummy.next);
}
相关推荐
不知名的老吴1 小时前
双栈秒杀表达式的生成方式
数据结构
故事和你912 小时前
洛谷-【动态规划1】动态规划的引入2
开发语言·数据结构·c++·算法·动态规划·图论
信奥胡老师4 小时前
B3968 [GESP202403 五级] 成绩排序
数据结构·算法
z200509305 小时前
今日算法(回溯算法)
数据结构·算法
m0_629494736 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒6 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
一路往蓝-Anbo7 小时前
第五章:如何对 HAL 库本身进行单元测试?
网络·数据结构·stm32·单片机·嵌入式硬件·单元测试·tdd
青山师7 小时前
B+树与InnoDB索引深度解析:数据库索引的底层原理与工程实践
数据结构·数据库·b树·性能优化·b+树·索引优化·mysql性能
tongluowan0077 小时前
数据结构 Bitmap(位图)完整详解
开发语言·数据结构·bitmap
代码中介商7 小时前
排序算法完全指南(五):快速排序深度详解
数据结构·算法·排序算法