ViviO
ViviO

Reputation: 43

Creating an insert method for Linked List Collection (Java)

I'm trying to create my own Linked List methods for a Collection of videogame titles/prices. I've made some progress with my add and delete methods, but I need to make one to insert one somewhere in the list that isn't just at the end. Either by using indexes or inserting after the other objects in the list. I can't seem to get it to work, though.

Here's what I have so far:

VideoGame.java

public class VideoGame {

private String name;
private Double price;

public VideoGame(String n, Double p)
    {
    name = n;
    price = p;
    }

public String getName() 
    {
    return name;
    }

public void setName(String name) 
    {
    this.name = name;
    }

public Double getPrice() 
{
    return price;
}

public void setPrice(Double price) 
{
    this.price = price;
}

@Override
public String toString() {
    return "Name: " + name + ", " + "Price: $"+price;
}
}

VideoGameNode

public class VideoGameNode 
{
public VideoGame data;


public VideoGameNode next;


public VideoGameNode(VideoGame s)
{
    data = s;
    next = null;


}


}

VideoGameList

public class VideoGameList {
private VideoGameNode list;


public VideoGameList()
{
    list = null;

}
//method to add entries into the collection (at the end each time)
public void add(VideoGame s)
   {
    VideoGameNode node = new VideoGameNode(s);
    VideoGameNode current;


  if (list == null)
     list = node;
  else
  {
     current = list;
     while (current.next != null)
        current = current.next;
     current.next = node;
  }
  }

I have a tester/driver program, but it's kind of irrelevant to what I need help doing right now. I can't seem to get an insert method to work properly. Does anyone have any ideas?

Upvotes: 1

Views: 6365

Answers (1)

ninja.coder
ninja.coder

Reputation: 9648

You can create an insert() method which also takes the position as an argument.

Inside this method you can write the similar code which you have written for add() method.

You just have to define a counter and check an additional condition inside the while loop for if that counter equals the position you passed as the argument. If any of the two conditions of your loop gets satisfied then it will be terminated.

Here is the code snippet:

public void insert(VideoGame s, int position) {
    if (null == list) {
        list = new VideoGameNode(s);
    } else {
        VideoGameNode current = list;
        int counter = 0;
        while (null != current.next && position > counter++)
            current = current.next;
        VideoGameNode newNode = new VideoGameNode(s);
        newNode.next = current.next;
        current.next = newNode;
    }
}

Upvotes: 1

Related Questions