17.在单链表中删除指定值的节点

【题目】

给定一个链表的头节点head和一个整数num,请实现函数将值为num的节点全部删除

【代码1】

时间复杂度O(n),空间复杂度O(n)

class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        ListNode cur = head;
        Stack<ListNode> stack = new Stack<>();
        while(cur != null){
            if(cur.val != val){
                stack.push(cur);
            }
            cur = cur.next;
        }
        while(!stack.isEmpty()){
            stack.peek().next = cur;
            cur = stack.pop();
        }
        return cur;
    }
}

【代码2】

时间复杂度O(n),空间复杂度O(1)

class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        while(head != null){
            if(head.val != val){
                break;
            }
            head = head.next;
        }
        ListNode cur = head;
        ListNode pre = head;
        while(cur != null){
            if(cur.val == val){
                pre.next = cur.next;
            }else{
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}

你可能感兴趣的:(程序员代码面试指南,算法)