链表相加(二)


代码求解

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);
}
相关推荐
benchmark_cc4 小时前
批量获取股票数据后,如何统一转换成 DataFrame?从数据结构到量化研究的完整实践
数据结构·python·数据分析·量化交易·股票数据·quantdash
啵啵啵鱼4 小时前
第三章 栈、队列和数组相关结构
java·数据结构·栈·队列
xys_6784 小时前
深挖数据结构:线性表(1)
数据结构
mmmmath_314 小时前
LeetCode.104.二叉树的最大深度
数据结构·leetcode
信奥卷王21 小时前
[GESP202509 六级] 划分字符串(含视频)
数据结构·算法
m0_7520356321 小时前
Redis 数据结构总结
数据结构·数据库·redis
tachibana221 小时前
Go 语言的 Map 是否是并发安全的?
开发语言·数据结构·后端·golang·go·语言
Logic1011 天前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
我命由我123451 天前
LRU 缓存淘汰策略
数据结构·redis·学习·mysql·算法·缓存·学习方法
垆边人似月.1 天前
华为题:合并区间
数据结构·c++·算法