Following our Binary Tree Implementation in Java, I put 5 mins of my time towards a small tutorial on ‘How to implement a Linked List in Java. Everything can be found in the Interview Question Repository on GitHub.
Implement a Linked List in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
/* * @Author: Ajk Palikuqi * * @Question: How to implement a Linked List in Java. * */ package IQLib.LinkedListLib; public class LinkedListNode { private int value; private LinkedListNode next; private LinkedListNode previous; public LinkedListNode(int newValue) { this(newValue, null, null); } public LinkedListNode(int newValue, LinkedListNode newNext) { this(newValue, newNext, null); } public LinkedListNode(int newValue, LinkedListNode newNext, LinkedListNode newPrevious) { value = newValue; setNext(newNext); setPrevious(newPrevious); } public int getValue() { return value; } public void setNext(LinkedListNode newNext) { next = newNext; if (newNext != null && newNext.previous != this) { newNext.setPrevious(this); } } public void setPrevious(LinkedListNode newPrevious) { previous = newPrevious; if (newPrevious != null && newPrevious.next != this) { newPrevious.setNext(this); } } } |
Now you should be able to implement a Linked List in Java on your own! Not that Linked Lists are one of the very basic data structures which will be very useful throughout your interviews. If you do not know what a Linked List is take a look at the wikipedia article LinkedList. If you would want to learn how to implement a linked list in another language, or do additional operations with linked lists in java, then hit me up and I will be happy to make a follow up post.
Hope you guys enjoyed it… and I’ll see you guys next time ;D
The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂
Latest posts by Ajk (see all)
- Find Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017