Linked List Java Tutorial

<aside> 📌 Linked List: storing list of data in memory requires each item to store information that indicates where the next item is stored. The additional information is a reference or pointer to a data location

</aside>


The linked list itself is an object, but it is full of nodes that are objects

public class LinkedList{
	private Node head;

	public LinkedList(){ //constructor
		head = null;
	}

	public void addAtFront(String str){
		Node newNode = new Node(str);
		newNode.setNext(head);
		head = newNode; //the only access to the list is from the head
	}

	public void remove(String str){
		///
	}

	public String toString(){
		Node current = head;
		String info = "";

		if(current == null){
			reutrn "No items";
		}

		info+=current.getData();

		while(current.getNext() != null){
			//then loop through the nodes
			current = current.getNext();
			info += current.getData();
		}
		//if its not empty, return the items there
		//if the head is null, there is nothing there 
		return info;
	}

	public class Node{
		private Node next;
		private String data;

		public Node(String newData){
			data = newData;
			next = null;
		}
		
		public void setNext(Node newNode){
			next = newNode;
		}	
		
		public Node getNext(){
			return next;
		}

		public String getData(){
			return data;
		}	

	}

}

//main class
public static void main(String[]args){
	LinkedList list = new LinkedList();
	
	list.addAtFront("Jainam");
	list.addAtFront("Jennifer");
	list.addAtFront("Samar");

	System.out.println(list); //prints out Samar, Jennifer, Jainam

	list.addAtFront("ALICE");
	list.addAtFront("ABBAS");

	System.out.println(list) //prints out ABBAS, ALICE, Samar, Jennifer, Jainam
}

Nested class is a class within a class, a member of the original class


add to front

Adds a new node to the front of the list

Untitled