Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts

Monday, August 20, 2012

Linked List Operations in Java Using LinkedList Utility Class


package com.test;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class LinkedListFunctions {

public static void main(String args[]){
LinkedList list=new LinkedList();

//Adding elements in Linked List
list.add(12);
list.add(17);
list.add(4);
list.add(45);
list.add(3);

// Printing elements in Linked List;
System.out.println(list);

//Printing the elements using iterator
Iterator itr=list.iterator();
while(itr.hasNext())
System.out.println(itr.next());

//Adding elements First and Last
list.addFirst(1);
System.out.println(list);

list.addLast(99);
System.out.println(list);

System.out.println("Get the size of List"+list.size());

//Sort the list using Collections Sort
Collections.sort(list);
System.out.println(list);

//Get the sublist from list
System.out.println(list.subList(2, 4));

//Stack Operations Using Linked List
System.out.println(list.peek());
System.out.println(list.poll());
System.out.println(list.pop());

}
}