I am trying to get the count of list. I wrote separate function to get the count. When I am calling this into the main, It is throwing error. error is
getCount is undefined for type LinkedList.
My code is
import java.util.*; import java.util.LinkedList.*; public class LengthCount { Node head; // Insert a new node from the front. public void push(int new_data){ Node new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function for getting count public int getCount(){ int count = 0; Node temp = head; while(temp != null){ count++; temp = temp.next; } return count; } public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(1); llist.push(3); llist.push(1); llist.push(2); llist.push(1); System.out.println("Counts of node is : "+llist.getCount()); // Error in this line } }
Can any body please help me
Answer
I guess you trying to get the length of list. Then use API. Here is your modified code
import java.util.*; public class LengthCount { public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(1); llist.push(3); llist.push(1); llist.push(2); llist.push(1); System.out.println("Counts of node is : "+llist.size()); }}