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

链表相加(二)

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

全部评论

相关推荐

Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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