What is LinkedListNode in Java

前端 未结 5 661
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 18:42

Excuse my ignorance but I am beginning to prepare for my first technical interview and came across this question and answer on the topic linkedlist

Question: Imp

5条回答
  •  心在旅途
    2021-02-14 19:14

    LinkedListNode is a class that you will define to hold data. To get your above example to work - I've quickly written this code (just to make you understand the simple concept) in which I am creating 3 nodes (which are linked to each other) and then deleting the middle one calling the deleteNode method that you have specified in your question.

    The code is pretty self explanatory. Let me know if this helps. Good Luck

    class LinkedListNode
    {
        public Object data;
        public LinkedListNode next;
    
        public LinkedListNode(Object data) {
        this.data = data;
        }
    }
    
    class DeleteNodeLinkedList
    {
        public static void main(String[] args) 
        {
            LinkedListNode node_1 = new LinkedListNode("first");        
            LinkedListNode node_2 = new LinkedListNode("second");
            node_1.next = node_2;
            LinkedListNode node_3 = new LinkedListNode("third");
            node_2.next = node_3;
    
            System.out.println("*** Print contents of linked list");
            LinkedListNode  current = node_1;
            while (current != null) {
                System.out.println(current.data);
                current = current.next;
            }
    
            System.out.println("*** Now delete second node");
            deleteNode(node_2);
    
            System.out.println("*** Print after deleting second node");
            current = node_1;
            while (current != null) {
                System.out.println(current.data);
                current = current.next;
            }
        }
    
        public static boolean deleteNode(LinkedListNode n) 
        {
            if (n == null || n.next == null) {
                return false; // Failure
            }
            LinkedListNode next = n.next;
            n.data = next.data;
            n.next = next.next;
            return true;
        }
    }
    

提交回复
热议问题