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

链表相加(二)

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;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-30 18:19
点赞 评论 收藏
分享
湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务