Friday, November 26, 2010

Linked List in Java


Linked List is a Dynamic Data Structure, allocates memory for any data item at run-time.  An array allocates memory for all its elements lumped together as one block of memory. In contrast, a linked list allocates space for each element separately in its own block of memory called a "linked list element" or "node".
Each node contains two fields:  a "data" field to store item data and a "next" field which is a pointer used to link one node to the next node. It can be represented as
       
In Java, Linked list can be implemented with the help of creating objects  of LinkedList class. LinkedList class implements the List interface for list operations, and permits all type elements (including null)  to be inserted. In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack and queue.
To create LinkedList object the following statement is used
LinkedList myList=new LinkedList();
The above statement creates an empty List then we can use the following functions
void add(int index,Object element): Inserts the specified element at the specified position in the list.
boolean add(Object o): Appends the specified element to the end of list
void addFirst(Object o): Inserts the given element at the beginning
void clear()Removes all of the elements from the list.
Object get(int index): Returns the element at the specified position.
Object getFirst(): Returns the first element in the list
Object getLast(): Returns the last element in the list
Object remove(int index):Removes the element at the specified position

No comments:

Post a Comment