[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/git-jhy/JavaArithmetic/master/src/LeetCode/LeetCode203.java [Back]  [Original]

package LeetCode;

public class LeetCode203 {

    // https://leetcode.com/problems/remove-linked-list-elements/description/
    // 
    // : O(n)
    // : O(1)

    public ListNode removeElements(ListNode head, int val) {

        // 
        while(head != null && head.val == val){
            ListNode node = head;
            head = head.next;
        }

        if(head == null)
            return head;

        ListNode cur = head;
        while(cur.next != null){
            if(cur.next.val == val){
                ListNode delNode = cur.next;
                cur.next = delNode.next;
            }
            else
                cur = cur.next;
        }
        return head;
    }

    // ()
    public ListNode removeElements2(ListNode head, int val) {

        // 
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;

        ListNode cur = dummyHead;
        while(cur.next != null){
            if(cur.next.val == val ){
                ListNode delNode = cur.next;
                cur.next = delNode.next;
            }
            else
                cur = cur.next;
        }

        return dummyHead.next;
    }

    // 
    public ListNode removeElements3(ListNode head, int val) {

        if(head == null)
            return head;

        // value
        ListNode res = removeElements3(head.next, val);

        if(head.val == val)
            return res;
        else{
            head.next = res;
            return head;
        }
    }
    // --->
    public ListNode removeElements4(ListNode head, int val) {

        if(head == null)
            return head;

        // 
        head.next = removeElements4(head.next, val);

        // 
        return head.val == val ? head.next : head;
    }


    public static void main(String[] args) {

        int[] nums = {1, 2, 6, 3, 4, 5, 6};
        ListNode head = new ListNode(nums);
        System.out.println(head);

        ListNode res = (new LeetCode203()).removeElements3(head, 6);
        System.out.println(res);
    }
}

Web Proxy Viewer  |  New URL  |  Original Page