题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 * @author Lu.F
 * @version 1.0
 * @date 2022/10/8 22:06
 */
public class Solution301 {

    /**
     * 运用栈 先进后出特点
     * @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;
        }

        // 栈
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();

        while (head1 != null){
            stack1.push(head1.val);
            head1 = head1.next;
        }

        while (head2 != null){
            stack2.push(head2.val);
            head2 = head2.next;
        }

        // 进位
        int temp = 0;
        ListNode pHead = new ListNode(-1);
        ListNode head = pHead.next;

        while (!stack1.isEmpty() || !stack2.isEmpty()){
            int val = temp;
            if (!stack1.isEmpty()){
                val += stack1.pop();
            }

            if (!stack2.isEmpty()){
                val += stack2.pop();
            }
            // 头插法
            temp = val/10;
            ListNode node = new ListNode(val%10);
            node.next = head;
            head = node;
        }

        // 头插法
        if (temp > 0){
            ListNode node = new ListNode(temp);
            node.next = head;
            head = node;
        }

        return head;
    }
}

全部评论

相关推荐

2024-12-25 09:09
四川师范大学 运营
想和你交朋友的潜伏者要冲国企:先去沃尔玛亲身感受标准化流程体系,一两年后再跳槽国内任何零售行业,可以有更大选择权吧?
点赞 评论 收藏
分享
明天不下雨了:兄弟你是我今天看到的最好看的简历(我说的是简历风格跟简历书写)把985 211再搞亮一点。投boss就说;您好,我华科(985)研二在读,本科211。对您的岗位很感兴趣,希望能获得一次投递机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务