Monday, April 28, 2025

Java OO Tutorial - LinkedList

A linked list is a data structure that represents a sequence of nodes, where each node points to the next node in the list. Each node in the list contains an element of data, as well as a reference to the next node in the list.

import java.util.LinkedList;

public class Main {	
	
	public static void main(String[] args) {
		
		LinkedList<String> pLanguages = new LinkedList<String>();
		
		pLanguages.add("Java");
		pLanguages.add("Lisp");
		pLanguages.add("C++");
		
		System.out.println(pLanguages);
		
		//Adding Stuff
		pLanguages.addFirst("Prolog");
		System.out.println(pLanguages);
		
		pLanguages.addLast("Ada");
		System.out.println(pLanguages);
		
		//Get Stuff
		
		System.out.println("First Element: " + pLanguages.getFirst());
		System.out.println("Last Element: " + pLanguages.getLast());
		System.out.println(pLanguages);
		
		//Remove Stuff
		pLanguages.removeFirst();
		pLanguages.removeLast();
		System.out.println(pLanguages);		
	}		
}

Our program here demonstrates the use of LinkedList in Java.

import java.util.LinkedList;

This line imports the LinkedList class from the Java.util package. 

public class Main {	

    public static void main(String[] args) {

The class Main is declared with a main() method inside. 

LinkedList<String> pLanguages = new LinkedList<String>();

A LinkedList object named pLanguages is created, which will contain strings. 

pLanguages.add("Java");
pLanguages.add("Lisp");
pLanguages.add("C++");

Elements are added to the LinkedList using the add() method. 

System.out.println(pLanguages);

This prints the LinkedList pLanguages to the console. 

pLanguages.addFirst("Prolog");
System.out.println(pLanguages);

pLanguages.addLast("Ada");
System.out.println(pLanguages);

Two new elements are added to the LinkedList at the beginning and the end of the list using the addFirst() and addLast() methods. 

System.out.println("First Element: " + pLanguages.getFirst());
System.out.println("Last Element: " + pLanguages.getLast());
System.out.println(pLanguages);

The first and last elements of the LinkedList are retrieved using the getFirst() and getLast() methods. 

pLanguages.removeFirst();
pLanguages.removeLast();
System.out.println(pLanguages);

Finally, the first and last elements are removed from the LinkedList using the removeFirst() and removeLast() methods. The resulting list is printed to the console using println().

The output of this program should be: 

[Java, Lisp, C++]
[Prolog, Java, Lisp, C++]
[Prolog, Java, Lisp, C++, Ada]
First Element: Prolog
Last Element: Ada
[Prolog, Java, Lisp, C++, Ada]
[Java, Lisp, C++]

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...