GitHub Account Google Scholar Account LinkedIn Account Twitter Account flickr Account vialab Research Group Profile Page

Remove Node at Position p in a Singly Linked List

Date: May 8, 2016

Both algorithms (methods) accomplish the same thing.
public Node removeA(int p) {

    if (head == null) {
        return null;

    } else if (p == 0) {

        Node temp = head;

        if (tail == head) {
            tail = head.next;
        }

        head = head.next;
        return temp;

    } else {

        int count = 1;
        Node prev = head;

        while (true) {

            if (count == p) {

                if (prev.next == null) {
                    return null;
                }

                Node temp = prev.next;
                prev.next = prev.next.next;

                if (prev.next == null) {
                    tail = prev;
                }

                return temp;
            }

            prev = prev.next;
            count++;
        }
    }
}

public Node removeB(int p) {

    Node cur = head;
    Node prev = null;
    int count = 0;

    while (true) {

        if (cur == null || count == p) {
            break;

        } else {

            prev = cur;
            cur = cur.next;
            count++;
        }
    }

    if (cur != null) {

        if (p == 0) {
            head = null;
            tail = null;

        } else {

            prev.next = cur.next;

            if (cur.next == null) {
                tail = prev;
            }
        }
    }

    return cur;
}