

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An example of implementing a singly linked list in java using the node and llist classes. The node class represents each node in the list, containing a name and a reference to the next node. The llist class manages the list, maintaining a reference to the head node and the list size. The main method in the listex class creates an empty list, adds three nodes with given names to the head of the list, and displays the list.
Typology: Study notes
1 / 2
This page cannot be seen from the preview
Don't miss anything!


public class Node { // Data part private String name; // Link to next private Node next; // Constructors Node() {name=""; next=null;} Node(String n) {name=n; next=null;} Node(String n, Node p){name=n; next=p;} // Readers public String getName(){return name;} public Node getNext(){return next;} // Writers public void setName(String n){name=n;} public void setNext(Node p) {next=p;} public void setNode(String n, Node p) {name=n; next=p;} }
public class LList { // Reference to head of the list. private Node head; // List size. private int size; // Constructor LList(){head=null; size=0;} // Add new node with specified name to head of the list. public void addFirst(String s) { head = new Node(s,head); size++;} // Display list public void display() { System.out.println("List contains "+size+" nodes."); Node p = head; while (p != null) { System.out.println(p.getName()); p = p.getNext(); // Move to next node. } } }
public class ListEx { public static void main(String[] args) { // Create empty list. LList list=new LList(); // Add three nodes; list.addFirst("Larry"); list.addFirst("Curly"); list.addFirst("Moe"); // Display what we've created. list.display(); } }