Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to insert data before another data in a linked list but when I insert data after specific data . Instead of inserted before it. It's going to insert after that specific data. Here is my code, need correction, and Thanks in advance.

public void InsertBefore(int key, int element) {

    Node current = head;
    Node prev = null;

    if (head != null) {

        while (current != null) {

            if (current.equals(key)) {

                Node n = new Node(element);
                n.next = current;

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

            prev = current;
            current = current.next;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

Make sure you have implemented the Node.equals() correctly or try this

 public static void InsertBefore(int key, int element) {

    Node current = head;
    Node prev = null;

    if (head != null) {
        while (current != null) {
            if (current.element == key) {
                Node n = new Node(element);
                n.next = current;

                if (prev != null) {
                    prev.next = n;
                } else {
                    head = n;
                }
                return;
            }

            prev = current;
            current = current.next;
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...