Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Jdk6 Linked List Example In Java

Related Tutorials


 
 

Share on Google+Share on Google+

Linked List Example In Java

Advertisement
This section will help you to understand LinkedList in Java. How to create LinkedList, how to Add element in LinkedList, how to Remove element from the LinkedList etc.

Linked List Example In Java

LikedList implements List interface which perform all operation  like add, remove, delete etc. LinkedList class provide  method to insert, remove , to get the element, insert at the beginning. These operation allow linkedList to use as stack, queue, dequeue. This class can implement dequeue interface which provide first in first out, for add, remove along with other stack operation. The operation which perform adding or removing element will traverse the element from beginning and end of the list.

LinkedList has following constructor:

  • LinkedList() : Create a empty linked list.
  • LinkedList(Collection c) : Create a linked list which initialize the element from collection.

LinkedList class define some useful method which manipulate and access the element.

Some of the element of linked list are as follows:

  • void addFirst(Object ob) : Add element to the beginning of the list.
  • void addLast(Object ob) : Add element at the last of the list.
  • Object getFirst() : To get the first element.
  • Object getLast() : To get the last element.
  • Object removeFirst():  To remove the first element from the List.
  • Object removeLast() : To remove the last element from the List.

The following program will illustrate the LinkedList example

import java.util.*;
public class LinkedListDemo {
	public static void main(String args[])
	{
		LinkedList list = new LinkedList();
		// add elements to the linked list
		list.add("W");
		list.add("B");
		list.add("K");
		list.add("H");
		list.add("L");
		list.addLast("Z");
		list.addFirst("A");
		list.add(1, "A2");
		System.out.println("Original contents of list: " + list);
		// remove elements from the linked list
		list.remove("B");
		list.remove(3);
		System.out.println("Contents of list after deletion: "+ list);
		// remove first and last elements
		list.removeFirst();
		list.removeLast();
		System.out.println("list after deleting first and last: "+ list);
		// get and set a value
		System.out.println("list after change: " + list);
		}
		
	}

Output from the program:

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 6, 2013

Related Tutorials

Discuss: Linked List Example In Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com