1+ //Author: Vaibhav Pandey
2+ //Date Created: 06/03/2022
3+ //Title: Implementing Linked List data structure in Java from scratch
4+
5+
6+ //Start of main LinkedList class
7+ public class LinkedList {
8+
9+ //Node class for storing current node's value and the address to the next node
10+ static class Node {
11+ Node next ;
12+ int value ;
13+
14+ //Constructor that initializes node's value
15+ public Node (int value ){
16+ this .value = value ;
17+ }
18+ }
19+
20+ //Initializing the first node to null
21+ Node first = null ;
22+
23+ //Function for adding elements at the front of the list
24+ public void addAtFront (Node node ){
25+ //Assign the next node's address to first and store the current node's address in first
26+ node .next = first ;
27+ first = node ;
28+ }
29+
30+ //Function for adding elements at the end of the list
31+ public void addAtEnd (Node node ){
32+ //If the list is already empty, just assign the first address to the current node
33+ if (first == null ){
34+ first = node ;
35+ }
36+ //If the list is not empty, traverse the list from the first element to the last element and add the current node at last
37+ else {
38+ Node ptr = first ;
39+ while (ptr .next != null ){
40+ ptr = ptr .next ;
41+ }
42+ ptr .next = node ;
43+ }
44+ }
45+
46+ //Function for removing the first element of the list
47+ public void removeFront (){
48+ //To remove the first element, just set the next element to first
49+ first = first .next ;
50+ }
51+
52+
53+ //Function to print the list
54+ public void print (){
55+ //For printing just traverse the list from first to last
56+ Node ptr = first .next ;
57+ System .out .print (first .value );
58+ while (ptr != null ){
59+ System .out .print (" -> " + ptr .value );
60+ ptr = ptr .next ;
61+ }
62+ System .out .println (" -> null" );
63+ //The last element of the list points to null
64+ }
65+
66+ //Main function to run the LinkedList class
67+ public static void main (String [] args ){
68+ LinkedList list = new LinkedList ();
69+ list .addAtEnd (new Node (5 ));
70+ list .addAtEnd (new Node (7 ));
71+ list .addAtFront (new Node (10 ));
72+ list .addAtEnd (new Node (2 ));
73+ list .print ();
74+ }
75+
76+ }
0 commit comments