The Linkedlist class
- The Linked list class extends abstract sequential list and implements the list interface.
- It provides a linked list data structure.
- It has two constructors are shown below.
- Linked List(): It builds an empty linked list
- Linked List (collecton c): this constructor builds a linked list that is initialized with elements of the collection c.
- In addition to the methods that it inherits, the linked list class defines some useful methods of its own, as shown below, for manipulating and accessing lists.
Voids addfirst (object obj):
In this adds elements to the start of the list.
Voids addlast (object obj):
In this adds elements to the last of the list.
Object getfirst ():
Returns the first element present in the list
Object getlast ():
Retrieves the last element from the list
Object removefirst ():
Removes or deletes the first element from the list
Object removelast ():
Removes the last element from the last
The following program illustrates several of the methods supported by the linked list.
Import java. Util.*;
Class linked List Demo
Public static void main (string args [ ])
Linked List ll = new linked list ();
ll. add ( “ MSD”);
ll. add ( “ SSA”);
ll. add ( “ MGR”);
ll. add ( “ PV”);
ll. add ( “ PS”);
ll. add last ( “ MSK”);
ll. add first ( “ MSS”);
ll. add ( 3,“ MSR”);
System. Out. Prinln(“ contents of list :” +ll);
ll. remove (“ PV”);
System. Out. Prinln(“ contents of list, after deletion :” +ll);
ll. remove first();
ll. remove last ();
System. Out. Prinln(“ after removing first and last elements :” +ll);
Object value = ll.get (1);
ll.set (1, (string) value+ “MSD”);
System. Out. Prinln(“list, after modifications:” +ll);
- The output of the above program is as shown below.
- Contents of the list: MSS MSD SSA MSR PS MSK
- CONTENTS OF THE LIST AFTER DELETION: MSS MSD MSR PS MSK
- After removing first and last elements: MSD SSA MSR PS
- List after modification: MSD SSA MSD MSR PS.