I was able to get the first value of the linked list but It only works in this scenario. How is it possible to make the getFirst() able to work for any number of values stored in the linked list?
This program outputs: First Number is --> 1
public class LinkedListFirst
{
public static void main(String[] args)
{
MyLinkedList list = new MyLinkedList();
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
list.getFirst();
}
}
class MyLinkedList
{
private class Node // inner class
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null; // initial value is null
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node(); // create new node
newNode.x = d; // init data field in new node
newNode.link = first; // new node points to first node
first = newNode; // first now points to new node
}
//----------------------------------
public void getFirst()
{
System.out.println( "First Number is --> " + first.link.link.x);
}
}