简体   繁体   中英

Displaying 1st node of a linked list

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

Based on your comments above, I think you're actually after the last item in the list.

Consider this method:

public void getLast()
{
    Node current = first;
    while(current.link != null){
        current = current.link;
    }
    System.out.println("First number is ---> " + current.x);
}

Some of your confusion may arise from the fact that you use the word 'first' too loosely. Yes, you did add the number 1 first , but since you add items to the beginning of the list , it is now the last item of the list.

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM