Home > Back-end >  How can I insert an Item to the front of the List?
How can I insert an Item to the front of the List?

Time:10-21

I have a method called "public void insertAt(int index, int item)". This method is meant to "Insert an item at position index, where the index is passed to the method" I have my code for this method down below. When I insert an Item at an Index it works unless it's the first item in the list. When I try to insert an item at the beginning of the list nothing happens. For example, If I had a list: "[9, 8, 15, 7, 5, 15, 19, 6, 19, 2]" and I want to insert the number "90" in the first node it should look like [90, 9, 8, 15, 7, 5, 15, 19, 6, 19, 2] but instead I get "[9, 8, 15, 7, 5, 15, 19, 6, 19, 2]". How can I fix this in my code so if I was to insert an item at the head it would move the Item I want inserted to be placed at the head and every other item to be shifted down the list?

import java.util.Random;

public class LinkedListOfInts {
    Node head;
    Node tail;

    private class Node {
        int value;
        Node nextNode;

        public Node(int value, Node nextNode) {
            this.value = value;
            this.nextNode = nextNode;
        }

    }

    public LinkedListOfInts(int N, int low, int high) {
        Random random = new Random();
        for (int i = 0; i < N; i  )
            this.addToFront(random.nextInt(high - low)   low);
    }

    public void addToFront(int x) {
        head = new Node(x, head);
    }

    public void insertAt(int index, int item) {
        Node temp = head;
        Node prev = null;
        int i = 0;
        for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
            if (index == i) {
                Node newItem = new Node(item, null);
                if (prev != null) {
                    prev.nextNode = newItem;
                }
                newItem.nextNode = temp;
            }
            if (temp.nextNode != null) {
                prev = temp;
                temp = temp.nextNode;
                i  ;
            }
        }
    }

    public String toString() {
        String result = "";
        for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
            if (!result.isEmpty()) {
                result  = ", ";
            }
            result  = ptr.value;
        }
        return "["   result   "]";
    }

    public static void main(String[] args) {
        LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
        System.out.println(list.toString());
        list.insertAt(0, 27);
        System.out.println(list.toString());
    }
}

CodePudding user response:

It's because you never connect it to the rest of the list when its the head. All you need to do is add a one-line else statement for when the previous Node is null, like so

       for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
               if (index == i) {
                    Node newItem = new Node(item, null);
                    if (prev != null) {
                         prev.nextNode = newItem;
                    } else {
                         head = newItem;
                    }
                    newItem.nextNode = temp;
                    break;

(I threw in the break for performance, no need to iterate through the rest of the values once you've inserted the new node)

CodePudding user response:

you can add condition if index == 0 then just add a new node in from of the list.

here is your function

public void insertAt(int index, int item) {
        if (index == 0) {
            Node node = new Node(item, null);
            node.nextNode = head;
            head = node;
        }
        else {
            Node temp = head;
            Node prev = null;
            int i = 0;
            for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
                if (index == i) {
                    Node newItem = new Node(item, null);
                    if (prev != null) {
                        prev.nextNode = newItem;
                    }
                    newItem.nextNode = temp;
                }
                if (temp.nextNode != null) {
                    prev = temp;
                    temp = temp.nextNode;
                    i  ;
                }
            }
        }
    }
  • Related