Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CPAN322 Java Application Programming
Lecture #5: Data Structure 2
Data structure is a construct used to organize and manage a collection of data.
There are two kinds of data structures: static and dynamic. Static data structures
have fixed size during the program execution. Dynamic data structure can grow
and shrink at run time. An array is an example of static data structure where as
vectors are example of dynamic data structure. In this Module we will study the
dynamic data structure: LinkedList, Stacks and Queues.
Abstract Data Type:
An Abstract Data Type is a collection of data and methods that operate on those
data. An abstract data type defines the fundamental operations on the data but
they do not specify an implementation. Normally ADT are defined using objects
because objects hide their implementations behind well defined interfaces.
ArrayLists, Linked lists, stacks and queues are examples of an ADT. An
abstract list, for example, is an ordered sequence of items. The elements of this
abstract list can be traversed using an iterator. The operations that can be used
on an abstract list are separated from the implementation of these operations.
The user of an abstract list doesn't need to be concerned with the
implementations of any operation.
Linked lists:
A Linked list is a data structures that consists of a sequence of links .Each link
stores an element and a reference to the next link in the sequence. This kind of
list is referred to as singly linked list where elements can be traversed only
forward.
There is another kind of linked lists known as doubly linked list. Doubly linked
lists stores two references, one to the next element, and one to the previous
element. This enable the elements to be traverse forward and backward using
an iterator.
Linked list enable us to remove and add elements without moving any existing
elements. When an element is added to or removed from a linked list , only the
link references of the neighboring elements need to be updated.
1
Elements access in linked list is slow, because they are accessed sequentially.
To access a certain element, you have to traverse through all the preceding
elements. Linked lists doesn't provide random access to its elements.
Java provide standard implementation for linked lists via the class LinkedList in
the package java.util. Following are some of the methods this class:
add (int index,Object element)
Inserts the specified element at the specified position in the list
add(Object o)
Appends the specified element to the end of the list
addAll(int index, Collection c)
Inserts all the elements in the collection to the specified position in the list.
AddAll(Collection c)
Appends all the elements in the collection to the end of the list
addFirst (Object o)
Inserts the specified element at the beginning of the list
addLast(Object o)
Inserts the specified element to the end of the list
clear()
Removes all the elements from the list
clone()
Returns a shallow copy of this list
contains(Object o)
Determines if the specified element is in the list
get(int index)
Returns the elements at the specified position in the list
2
getFirst()
Returns the first element in the list
getLast()
Returns the last element in the list
remove(int index)
Removes the element at the specified position from the list.
remove(Object o)
Removes the first occurrence of of the specified element from the list.
RemoveLast()
Removes and returns the last element from the list.
RemoveFirst()
Removes and returns the first element from the list.
size()
Returns the number of elements in the list.
toArray()
Returns an array containing all the elements in the list.
listIterator()
Returns a list iterator of the elements in the list.
indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1
if the List does not contain this element.
Lets start an example by defining a linked list called list:
3
String r[]={"cust1","cust2","cust3","cust4","cust5"};
LinkedList list=new LinkedList(Arrays.asList(r));
To add a new element to the beginning of the list, we use addFirst method:
list.addFirst("cust6");
To add a new element to the end of the list, we use addLast method:
list.addLast("cust16");
The following code shows how to traverse the list forward :
ListIterator iter=list.listIterator();
whlie (iter.hasNext()
{
Object ob=iter.next();
}
To traverse the linked list backward, we use the following code:
ListIterator iter=list.listIterator();
while (iter.hasPrevious())
{
Object ob=iter.previous();
}
To get the first element in the list:
list.getFirst();
To get the last element in the list:
list.getLast();
4
Stacks:
A stack is a constrained version of a linked list where new elements can be
added to the top of the stack or removed from the top of the stack. Stacks are
referred to as last in first out data structure (LIFO). The last node in the stack is
set to null in order to indicate the end of the stack.
Many programming languages uses stacks to perform basic operations such as
arithmetic operations or methods call. Also a block of computer memory can be
represented using a stack.
Stacks are implemented in the Java standard class library via the class Stack in
the package java.util. The main two methods in the Stack class are push and
pop: push method add a new element to the top of the stack, and pop method
removes an element form the top of the stack and return this element.
Queues:
A queue represents a waiting line. Insertions are made at the tail (back) of the
queue and deletions are made at the head (front) of the queue. Queues are
referred to as first in first out data structure (FIFO) .There is no implementation in
the standard library for a queue, but you can create your own (see example 4 ).
Queues also have many applications. For example a shared printer in a multiusers environment uses a queue to store users print jobs. The first job to come is
the first to be processed.
Examples:
Ex1:lnkListEx.java
In this example we will explore some of the main methods of the LinkedList
class:
5
import java.util.*;
public class linkedListEx
{
private LinkedList list;
public linkedListEx()
{
String r[]={"cust1","cust2","cust3","cust4","cust5"};
list=new LinkedList(Arrays.asList(r));
try
{
System.out.println("First Element in the list is "+ list.getFirst());
System.out.println("Last Element in the list is "+ list.getLast());
list.add("cust6");
list.remove("cust3");
list.add(1,"cust22");
list.set(1," new cust");
ListIterator iter=list.listIterator();
while (iter.hasNext())
{
System.out.println(iter.next());
}
System.out.println("The size of the list is "+ list.size());
System.out.println(list.contains("cust1")?"The element cust 1 is contained
in the list is ":"The element cust 1 is contained in the list is ");
}
catch(NoSuchElementException nse)
{
System.out.println(nse.toString()); }
}
public static void main(String args[])
{
new linkedListEx();
}
}
Ex2:
To understand the structure and the operations of a linked list, we will create a
custom implementation for a linked list. The linked list is an ADT. The operations
that can be performed on the linked list are defined in an interface called
ListInterface.java:
public interface ListInterface
{
6
boolean contains(Object o);
int size();
Object getFirst();
Object getLast();
void addLast(Object o);
void addFirst(Object o);
Object removeFirst();
Object removeLast();
CustomListIterator listIterator();
}
CustomListIterator is an interface that defines the operations that can be
performed when we iterate through the linked list. Notice that not all of the
methods of the list iterator are defined.
public interface CustomListIterator
{
Object next();
boolean hasNext();
void set(Object o);
void add(Object o);
void remove();
}
Then we will provide an implementation for the linked list via the class
CustomLinkedList.java. The ListInterface methods are implemented in an
inner class called LinkListIterator:
import java.util.*;
public class CustomLinkedList implements ListInterface
{
/*
Define a link object that stored a data object an a reference to the next link .
*/
private class Link
{
public Object data;
public Link next;
}
7
// References to the first link and the last link in the list
private Link first;
private Link last;
// construct an empty list
public CustomLinkedList()
{
first=last=null;
}
/*
Clear the list by traversing all the elements in the list and removing them
one by one
*/
public void clear()
{
CustomListIterator iter=listIterator();
while (iter.hasNext())
{
iter.next();
removeFirst();
}
}
/*
Determine if an element is contained in the list
*/
public boolean contains(Object o)
{
boolean found=false;
// set the current link to the first link.
Link current=first;
/*
Traverse through the list links and test their data. If a match is found,
return true, otherwise return false.
*/
while (current.next !=last)
{
if (current.data==o)
{
found=true;
break;
}
current=current.next;
}
return found;
8
}
/*
Count the number of links in the list
*/
public int size()
{
int i=0;
CustomListIterator iter=listIterator();
while (iter.hasNext())
{
i++;
iter.next();
}
return i;
}
/*
Return the first element in the list
*/
public Object getFirst()
{
if (first==null) throw new NoSuchElementException ();
return first.data;
}
/*
Return the last element in the list. If the last element is not defined, then we
return the first element.
*/
public Object getLast()
{
if (last==null)
return getFirst();
else
{
return last.data;
}
}
/*
To add a new element to the list, the link of the last element in the list must
reference the new element, and the new element becomes the last element
in the list.
*/
9
public void addLast(Object o)
{
if(first==null) addFirst(o);
else
{
Link newLink=new Link();
newLink.data=o;
last.next=newLink;
last=last.next;
}
}
/* Add an element to the beginning of the list
If the list is empty, then just add the new element. If the list is not empty,
the new element becomes the first element in the list and the old first
element becomes the next element.
*/
public void addFirst(Object o)
{
if(first==null)
{
Link newLink=new Link();
newLink.data=o;
first=last=newLink;
}
else
{
Link newLink=new Link();
newLink.data=o;
newLink.next=first;
first=newLink;
}
}
/* Remove the first element from the list
First we have to save the data of the first element in order to be returned as
the method result. To remove the first element, the link of the first element
must reference the second element in the list.
*/
public Object removeFirst()
{
if (first==null) throw new NoSuchElementException ();
Object ob=first.data;
10
first=first.next;
return ob;
}
/*
Remove the last element from the list
Save the data of the last element in order to be returned as the method
result. To remove the last element, the link of the previous element must
reference to null.
*/
public Object removeLast()
{
if (first==null) throw new NoSuchElementException ();
Object ob=last.data;
Link current=first;
while (current.next !=last)
{
current=current.next;
}
current.next=null;
return ob;
}
// return an iterator object
public CustomListIterator listIterator()
{
return new LinkedListIterator();
}
/* An inner class to implement methods defined in the interface
CustomListIterator
*/
private class LinkedListIterator implements CustomListIterator
{
/*
Maintain a reference to the current and the previous position in the link
*/
private Link currentPosition;
private Link previousPosition;
public LinkedListIterator()
{
11
// Initialize the current and the previous positions
currentPosition =null;
previousPosition=null;
}
/*
Return the data of the next element in the list. This method should be
called only when the iterator is not at the end of the list.
Store the current position, advance the current position to the next position
and return the data of the current position. If the current position is null,
then we are at the beginning of the list.
*/
public Object next()
{
if(!hasNext()) throw new NoSuchElementException ();
previousPosition=currentPosition;
if(currentPosition==null)
currentPosition=first;
else
currentPosition=currentPosition.next;
return currentPosition.data;
}
/*
Change the data stored in the previously visited element.
*/
public void set(Object o)
{
if (currentPosition==null) throw new NoSuchElementException();
currentPosition.data=o;
}
/*
Add an element after the current position in the list.
If we are at the beginning of the list, then just add the new element to the
beginning of the list. If we are in the middle of the list, then the link of the
new element must reference the next element in the list and the link of the
current element must reference the new element.
*/
public void add(Object o)
{
if (currentPosition==null)
{
addFirst(o);
currentPosition=first;
}
12
else
{
Link newLink= new Link();
newLink.data=o;
newLink.next=currentPosition.next;
currentPosition.next=newLink;
currentPosition=newLink;
}
previousPosition=null;
}
/*
Removing an element in the middle of the list.
If we are at the beginning of the list, then we just remove the first element.
If we are in the middle of the list, the link of the previous and the next
elements must be updated such that the link of the previous element must
reference the next element instead of the referencing the current element.
*/
public void remove()
{
if (currentPosition==first)
{
removeFirst();
currentPosition=first;
}
else
{
if(previousPosition==null)
throw new IllegalStateException();
previousPosition.next=currentPosition.next;
currentPosition=previousPosition;
}
previousPosition=null;
}
// Determine if there is an element after the current position of the iterator.
public boolean hasNext()
{
if (currentPosition==null)
return first !=null;
else
return currentPosition.next !=null;
}
}
}
13
Following is a test program called linkedListIMplTest.java:
import java.util.*;
public class linkedListImplTest
{
CustomLinkedList list;
public linkedListImplTest()
{
list = new CustomLinkedList();
list.addFirst("Item 4");
list.addFirst("Item 3");
list.addFirst("item 2");
list.addFirst("Item 1");
list.addLast("item 5");
System.out.println("First Element in the list is "+ list.getFirst());
System.out.println("Last Element in the list is "+ list.getLast());
CustomListIterator iterator = list.listIterator();
iterator.next();
iterator.next();
iterator.remove();
iterator.add("Item 6");
iterator.add("Item 7");
System.out.println("The size of the list is "+ list.size());
System.out.println(list.contains("Item 3") ? "The element Item 3 is
contained in the list ":" The element Item 3 is not contained in the list ");
// print all elements
iterator = list.listIterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
public static void main(String args[])
{
new linkedListImplTest();
}
}
Ex3:
In this example we will provide a custom implementation to a stack. The
approach is similar to Ex2
14
First we start be defining a custom list iterator interface called
CustomListIterator.java. This interface defines the operations that can be used
with an iterator on the stack :
public interface CustomListIterator1
{
Object next();
boolean hasNext();
}
We will define the following operations to be performed as well on the stack:
public interface StackInterface
{
void push (Object o);
Object pop();
Object peek();
boolean empty();
int size();
CustomListIterator1 listIterator();
}
Then we provide an implementation to the stack via the class
CustomStack.java:
import java.util.*;
public class CustomStack implements StackInterface
{
private class Link
{
public Object data;
public Link next;
}
private Link first;
private Link last;
public CustomStack()
{
first=last=null;
}
public void push (Object o)
15
{
if(first==null)
{
Link newLink=new Link();
newLink.data=o;
first=last=newLink;
}
else
{
Link newLink=new Link();
newLink.data=o;
newLink.next=first;
first=newLink;
}
}
public Object pop()
{
if (first==null) throw new NoSuchElementException ();
Object ob=first.data;
first=first.next;
return ob;
}
public Object peek()
{
return first.data;
}
public boolean empty()
{
if (first==null) return true;
else
return false;
}
public int size()
{
int i=0;
CustomListIterator1 iter=listIterator();
while (iter.hasNext())
{
i++;
iter.next();
}
return i;
}
public CustomListIterator1 listIterator()
{
return new LinkedListIterator();
16
}
private class LinkedListIterator implements CustomListIterator1
{
private Link currentPosition;
private Link previousPosition;
public LinkedListIterator()
{
currentPosition =null;
previousPosition=null;
}
public Object next()
{
if(!hasNext()) throw new NoSuchElementException ();
previousPosition=currentPosition;
if(currentPosition==null)
currentPosition=first;
else
currentPosition=currentPosition.next;
return currentPosition.data;
}
public boolean hasNext()
{
if (currentPosition==null)
return first !=null;
else
return currentPosition.next !=null;
}
}
public static void main(String args[])
{
new CustomStack();
}
}
Following is a test program called stackEx.java:
import java.util.*;
public class stackEx
{
CustomStack stack;
17
public stackEx()
{
try
{
stack= new CustomStack();
stack.push("cust222");
stack.push("cust333");
stack.push("cust444");
stack.push("cust555");
stack.push("cust666");
System.out.println("The size of the stack is "+stack.size());
CustomListIterator1 iter=stack.listIterator();
while (iter.hasNext())
{
System.out.println("element is "+iter.next());
}
System.out.println(stack.pop() +" is poped from the stack");
System.out.println(stack.peek() +" is the first element in the stack");
System.out.println("The size of the stack is "+stack.size());
System.out.println(stack.empty()?" Stack is empty ":" Stack is not empty");
}
catch(NoSuchElementException nse)
{
System.out.println(nse.toString()); }
}
public static void main(String args[])
{
new stackEx();
}
}
Ex4:
This example provide a queue implementation. We will use the list iterator
interface created in Ex3.
public interface QueueInterface
{
void enqueue (Object o);
18
Object dequeue();
Object peek();
boolean empty();
int size();
CustomListIterator1 listIterator();
}
The interface QueueInterface defines the rest of the operations that can be
performed on the queue:
import java.util.*;
public class Queue implements QueueInterface
{
private class Link
{
public Object data;
public Link next;
}
private Link first;
private Link last;
public Queue()
{
first=last=null;
}
public void enqueue (Object o)
{
if(first==null)
{
Link newLink=new Link();
newLink.data=o;
first=last=newLink;
}
else
{
Link newLink=new Link();
newLink.data=o;
last.next=newLink;
19
last=last.next;
}
}
public Object dequeue()
{
if (first==null) throw new NoSuchElementException ();
Object ob=first.data;
first=first.next;
return ob;
}
public Object peek()
{
return first.data;
}
public boolean empty()
{
if (first==null) return true;
else
return false;
}
public int size()
{
int i=0;
CustomListIterator1 iter=listIterator();
while (iter.hasNext())
{
i++;
iter.next();
}
return i;
}
public CustomListIterator1 listIterator()
{
return new LinkedListIterator();
}
private class LinkedListIterator implements CustomListIterator1
{
private Link currentPosition;
private Link previousPosition;
public LinkedListIterator()
{
currentPosition =null;
previousPosition=null;
}
20
public Object next()
{
if(!hasNext()) throw new NoSuchElementException ();
previousPosition=currentPosition;
if(currentPosition==null)
currentPosition=first;
else
currentPosition=currentPosition.next;
return currentPosition.data;
}
public boolean hasNext()
{
if (currentPosition==null)
return first !=null;
else
return currentPosition.next !=null;
}
}
}
And here is a test program called queueEx.java:
import java.util.*;
public class queueEx
{
Queue queue;
public queueEx()
{
try
{
queue= new Queue();
queue.enqueue("cust222");
queue.enqueue("cust333");
CustomListIterator1 iter=queue.listIterator();
while (iter.hasNext())
{
System.out.println("element is "+iter.next());
}
System.out.println(queue.dequeue() +" is removed from the queue");
System.out.println(queue.peek() +" is the first element in the stack");
System.out.println("The size of the stack is "+queue.size());
System.out.println(queue.empty()?" Stack is empty ":" Stack is not
21
empty");
}
catch(NoSuchElementException nse)
{
System.out.println(nse.toString());
}
}
public static void main(String args[])
{
new queueEx();
}
}
22