Docsity

Linked List Implementation in Java - Prof. S. F. Weiss, Study notes of Computer Science

Toggle sidebar
bg1
401-43.1
Linked list example
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.
}
}
}
pf2

Partial preview of the text

Download Linked List Implementation in Java - Prof. S. F. Weiss and more Study notes Computer Science in PDF only on Docsity!

Linked list example

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