链表相加(二)


代码求解

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 小时前
单链表专题(完整代码版)
数据结构·算法·链表
Morwit2 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
田梓燊5 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
葳_人生_蕤5 小时前
hot100——栈和队列
数据结构
历程里程碑7 小时前
二叉树---二叉树的中序遍历
java·大数据·开发语言·elasticsearch·链表·搜索引擎·lua
Meme Buoy8 小时前
18.补充数学1:生成树-最短路径-最大流量-线性规划
数据结构·算法
汀、人工智能8 小时前
[特殊字符] 第89课:岛屿数量
数据结构·算法·数据库架构·图论·bfs·岛屿数量
九英里路8 小时前
cpp容器——string模拟实现
java·前端·数据结构·c++·算法·容器·字符串
2401_892070988 小时前
顺序栈(动态数组实现) 超详细解析(C++ 语言 + 可直接运行)
数据结构·c++·顺序栈
漫霂8 小时前
二叉树的翻转
java·数据结构·算法