Java-LinkedList

The LinkedList class implements the List interface. Actuallly, the LinkedList class provides a linked-list data structure. Two important forms of the constructor of this class are as follows:

LinkedListList()
LinkedList ( Collection c )

When we use the first form of the constructor, an empty linked list will be formed. The second form of the constructor initializes the elements of the newly formed linked list by using the elements of the collection c.

The addFirst() method adds elements to the start of a linked list, the addLast() method adds elements to the end of a linked list.

The get() method Returns the element at the specified position in this list, the set() method replaces the element at the specified position on list with the specified element.

The removeFirst() method removes the first element, the removeLast() method removes the last element in a linked list.

Program

0

Program Source

import java.util.LinkedList;

public class Javaapp {

    public static void main(String[] args) {
        
        LinkedList list1 = new LinkedList();
        list1.add("CCCC");
        list1.add("DDDD");
        list1.add("EEEE");
        list1.add("FFFF");
        list1.add(0,"BBBB");
        list1.addFirst("AAAA");
        list1.addLast("GGGG");
        System.out.println("list1 = "+list1);
        
        list1.removeFirst();
        System.out.println("list1 = "+list1);
        
        list1.removeLast();
        System.out.println("list1 = "+list1);
        
        String getstr = list1.get(3);
        System.out.println("getstr = "+getstr);
        
        list1.set(0,"AAAA");
        System.out.println("list1 = "+list1);
    }
}

Leave a Comment