Cracking the coding interview--Q2.3

Implement an algorithm to delete a node in the middle of a singly linked list,
given only access to that node.
EXAMPLE
Input: the node c from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a- >b- >d->e

删除链表中的一个节点,但并没有给出链表的头结点,而是只能访问要删除的这个节点。

 

解答:

将待删除的下一个节点copy到当前节点,然后删除下一个节点。要单独考虑待删除的是链表尾或者链表头的情况。链表头没有特别影响,而如果是链表尾的话,一开始想的是直接将该节点赋值为null,但是测试时发现没有效果。 看书中说如果是链表尾是不能删除的,要向面试官指出这个问题,或者将该节点的数据标记成一个特殊的值表示这个节点是个虚假不用的节点。

public class Main {

    public static void appendToTail(List head, int d) {

        List end = new List(d);

        List n = head;

        while (n.next != null) {

            n = n.next;

        }

        n.next = end;

    }



    public static void print(List head) {

        List n = head;

        System.out.print("{");

        while (n != null) {

            if (n.next != null)

                System.out.print(n.data + ", ");

            else

                System.out.println(n.data + "}");

            n = n.next;

        }

    }



    public static boolean revomeNode(List node) {

        if (node == null || node.next == null) {

            return false;

        } else {

            node.data = node.next.data;

            node.next = node.next.next;

            return true;

        }

    }



    public static void main(String args[]) {

        List list = new List(0);

        appendToTail(list, 1);

        appendToTail(list, 2);

        appendToTail(list, 3);

        appendToTail(list, 4);

        appendToTail(list, 5);

        appendToTail(list, 6);

        appendToTail(list, 7);

        appendToTail(list, 8);

        appendToTail(list, 9);

        print(list);

        List node = list;

        for(int i = 0; i < 9; i++)

            node = node.next;

        System.out.println(revomeNode(node));

        print(list);

    }

}



class List {

    int data;

    List next;



    public List(int d) {

        this.data = d;

        this.next = null;

    }

}

 

你可能感兴趣的:(interview)