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

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

java - How to insert a data before another one in Linked list?

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;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...