public class LinkedList extends AbstractSequentialList implements List
ü A linked-list data structure is a list with each item having a link to the next item.
ü There can be linear linked lists or circular linked lists.
ü Linear linked lists end at some point whereas circular linked lists have the last element pointing back to the first element thus forming a circular chain. Extends AbstractSequentialList and implements the List interface.
ü These operations allow linked lists to be used as a stack, queue.
Constructor
|
LinkedList() Constructs an empty list.
|
LinkedList(Collection<? extends E> c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
|
Some Important Methods
| |
void
|
addFirst(E o) Inserts the given element at the beginning of this list.
|
void
|
addLast(E o) Appends the given element to the end of this list.
|
E
|
getFirst() Returns the first element in this list.
|
E
|
getLast() Returns the last element in this list.
|
E
|
removeFirst() Removes and returns the first element from this list.
|
E
|
removeLast() Removes and returns the last element from this list.
|
Example:
import java.util.LinkedList;
public class LinkedListDemo
{
{
public static void main(String[] args)
{
{
LinkedList llstStars = new LinkedList();
llstStars.add("Harry");
llstStars.add("Emaini");
llstStars.add("Voldmort");
llstStars.add("Severes");
llstStars.add("Dumbuldore");
System.out.println("Contents of the list :");
System.out.println(llstStars);
llstStars.addFirst("Potter");
llstStars.addLast("Slytherin");
System.out.println("\nContents of the list after adding Potter and Slytherin :");
System.out.println(llstStars);
System.out.println();
llstStars.remove(2);
llstStars.remove("Emaini");
System.out.println("\nContents of the list after deleting Emaini and element at index 2 :");
System.out.println(llstStars);
String strTemp = (String) llstStars.get(3);
llstStars.set(3, strTemp + " snape");
System.out.println("\nContents of the list after modifying 4th element :");
System.out.println(llstStars);
}
}
0 comments :
Post a Comment