Way To use Linked List in Java



The LinkedListclass extends AbstractSequentialListand implements the List, Deque, and
Queue interfaces.At  begin of a list you can use addFirst( ) orofferFirst( )  to add first element .
To add elements to the end of the list, use addLast( ) or offerLast( ).In order to obtain the first element, we can use  getFirst( ) or peekFirst( ).For obtaining last element, use   getLast( ) or peekLast( ). In the way to remove the first element, use removeFirst( ) or pollFirst( ). To remove the last element, use removeLast( ) or pollLast( ).
// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;
importjava.util.*;
/**
 *
 * @author allinalljava
 */
public class JavaLinkedList {

public static void main(String args[]) {
// Create a linked list.
LinkedListlinkedList= new LinkedList();
// Add elements to the linked list.
linkedList.add("A");
linkedList.add("L");
linkedList.add("L");
linkedList.add("I");
linkedList.add("N");
linkedList.addLast("A");
linkedList.addFirst("L");
linkedList.add(1, "L");
System.out.println("Original contents of ll: " + linkedList);
// Remove elements from the linked list.
linkedList.remove("N");
linkedList.remove(3);
System.out.println("Contents of ll after deletion: "
+ linkedList);
// Remove first and last elements.
linkedList.removeFirst();
linkedList.removeLast();
System.out.println("ll after deleting first and last: "
+ linkedList);
// Get and set a value.

String val = linkedList.get(2);
linkedList.set(2, val + " Changed");
System.out.println("ll after change: " + linkedList);
}
}

Output 
Original contents of ll: [L, L, A, L, L, I, N, A] 
Contents of ll after deletion: [L, L, A, L, I, A] 
ll after deleting first and last: [L, A, L, I]
 ll after change: [L, A, L Changed, I]
raja P Web Developer

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...