Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get method in a implemented Linked List, Java

I need to implement a Linked List of integers from zero (not using existing LinkedList class).

This is the code:

A single Link class

public class Link {
    public int data;
    public Link nextLink;

    public Link(int d1) {
        data = d1;      
    }

    public void printListElements(){
        System.out.println(data);
    }
}

and the LinkedList class

public class LinkedList {
    private Link first;
    public LinkedList(){
        first = null;
    }

    public void add(int data1){
        Link linklist = new Link(data1);
        linklist.nextLink = first;
        first = linklist;
    }

    public void printList(){
    Link current=first;
    System.out.println("List Elements are ");
    while(current!=null){
       current.printListElements();
       current=current.nextLink;
    }
  }
}

As you see it has already add and printList method. But how do i make a get() method, which returns a value of a specific index.

This is what i mean:

public static void main(String args[]){
    LinkedList MyList = new LinkedList();

    MyList.add(1);
    MyList.add(2);
    MyList.add(3);
    MyList.add(4);

    System.out.println("MyList.get(0)"); // should get 1
        System.out.println("MyList.get(1)"); // should get 2 etc
}

Thank You in advance.

like image 259
user1714960 Avatar asked Dec 07 '22 11:12

user1714960


2 Answers

Well, since it's a linked list, you don't have any way to directly access any element except the first one, right? So the only way to do it is to start there and step through (by successively following the links to the next element) until you reach the element specified by the index, and then return that. The easiest way to do that is with a loop.

like image 197
jonvuri Avatar answered Dec 20 '22 05:12

jonvuri


You can't do that with your current implementation. Because you are adding every new node as the head node.

If you change your add() so that every new node is added as the last node then you can do that using your index value passed to get() as the loop counter.

like image 42
P.P Avatar answered Dec 20 '22 05:12

P.P