Linked List

Unless you are doing some fairly low level programming I doubt you will ever really have a good excuse to code your own linked list. If you are building some libraries that implement queues or thread libraries or something like that then maybe but that’s a rare form of development these days.

Linked lists are a great thing to learn and make for a host of good examples when learning how to program. They are conceptually simple but have many pitfalls and ways to expand and improve and learn about how to write programs. They make you get in touch with a lot of core issues in development that you aren’t used to thinking about outside of development. Because of that they are invaluable to learn about and make for good interview questions. That said, it is pretty unusual to actually code your own linked list in a professional job. There already exist libraries that implement linked lists under the covers that you use instead. Trust me, those libraries are way more efficient, thorough, fault-tolerant and useful than something you cook up on you own.

import java.util.LinkedList;

public class LinkedListExample {
	public static void main(String[] args) {

		LinkedList<Integer> linkedList = new LinkedList<Integer>();

		linkedList.add(23);
		linkedList.add(24);
		linkedList.add(25);

		System.out.println(linkedList);

		System.out.println("add first");
		linkedList.addFirst(65);
		System.out.println(linkedList);

		System.out.println("add last");
		linkedList.addLast(66);
		System.out.println(linkedList);

		System.out.println("remove first");
		int element = linkedList.removeFirst();
		System.out.println("element removed " + element);
		System.out.println(linkedList);

		System.out.println("remove last");
		int element1 = linkedList.removeLast();
		System.out.println("element removed " + element1);
		System.out.println(linkedList);
	}

}
[23, 24, 25]
add first
[65, 23, 24, 25]
add last
[65, 23, 24, 25, 66]
remove first
element removed 65
[23, 24, 25, 66]
remove last
element removed 66
[23, 24, 25]

Last updated