An implementation of a linked list in Java
Linked List
A linked list is a data structure consisting of nodes. Each node has a variable pointing to the node next to it. This makes the linked list a way of storing data in a sequence. This may sound similar to an array. It is. However, an array has a fixed size, making insertion a little trickier. With a linked list, the number of nodes can change to however many we want and insertion is as easy as changing the pointing variable of the node before which you would like to insert the new node.
Linked lists can also be used to implement more complex data structures such as trees and graphs.
An interest in the data structure of linked lists in general and a new introduction to the Java programming language sparked my interest in implementing this in Java. Having done some projects in C++, I had already begun thinking up a way to do this in C++. But doing it with Java, presented some new learnings to me, mainly concerned with the structure of the program and the way Java files are executed in VS Code.
Setting up the classes:
class Node { int value; //data stored in the node Node next; //pointing variable aka reference to the next node Node(int value) { this.value = value; //constructor for node } } class LinkedList { Node head; LinkedList() { this.head = null; //constructor for a linked list } public void insert(int value) { Node newNode = new Node(value); if(head == null) { head = newNode; //if list is empty } else { Node currentNode = head; while(currentNode.next != null){ currentNode = currentNode.next; } currentNode.next = newNode; //link the newNode to the last node } } public void print() { Node currentNode = head; //begin at head while(currentNode != null) { System.out.print(currentNode.value + " -> "); currentNode = currentNode.next; } System.out.println("null"); } }
Setting up the test file:
class test { public static void main(String[] args) { LinkedList demonstration = new LinkedList(); demonstration.insert(2); demonstration.insert(4); demonstration.print(); } }
Comments
Post a Comment