题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

直接使用栈进行去重

 Stack<Integer> stack = new Stack<>();
        ListNode root = new ListNode(-1);
        ListNode cur = head, p;
        stack.push(root.val);
        while (cur != null){
            if (cur.val != stack.peek()){
                p = cur;
                stack.push(p.val);
                cur = cur.next;
            }else {
                int s = stack.pop();
                while (cur != null && cur.val == s){
                    cur = cur.next;
                }
            }
        }
        root = null;
        while (!stack.isEmpty()){
            int s = stack.pop();
            ListNode node = new ListNode(s);
            node.next = null;
            if (root == null){
                root = node;
            }else {
                node.next = root;
                root = node;
            }
        }
        return root.next;
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务