Professional Documents
Culture Documents
What is List?
A list is a sequential data
structure.
It differs from the stack and
queue data, structures in that
additions and removals can be
made at any position in the list.
List operations
Add : adds a new node
Set : update the contents of a
node
Remove : removes a node
IsEmpty : reports whether the list is
empty
IsFull : reports whether the list is
full
Initialize : creates/initializes the list
Destroy : deletes the contents of the
list (may be implemented by re-
initializing the list)
Illustration/example
Initialize(L)
Create a new empty List named L
Add(1,X,L)
adds the value X to list L at position 1 (the start of the list
is position 0), shifting subsequent elements up
1. Initialiaze(L) <empty> -
2. Add(0,A,L) A -
3. Add(0,B,L) B A -
4. Add(1,C,L) B C A -
5. Set(1,N,L) B N A -
6. Add(1,D,L) B D N A -
7. Remove(A,L) B D N A
8. Set(3,I,L) B D N I -
9. Remove(D,L) BN I D
10. Remove(N,L) BI N
Exercise: List Operation
What would the contents of a list be after the following
operations?
Initialise(L)
Add(0,A,L)
Add(0,F,L)
Add(1,X,L)
Add(1,G,L)
Add(3,P,L)
Add(2,V,L)
Set(3,K,L)
Set(0,H,L)
Remove(V,L)
Remove(P,L)
HGKA
If the new node is to be added at the end of the list, then the
NextNode of the last element is set to refer to the new
node.
Adding a node (3)
A possible algorithm (pseudocode) for the Add operation
Add(index,
Add(index, Data, LinkedList)
Declare NewNode and initialise NewNode.DataItem with data
If(List.isEmpty)
Set NewNode.NextNode to NULL
Copy NewNode to LinkedList.Head
Else
If (index is 0)
Copy LinkedList.Head to NewNode.NextNode
Copy NewNode to LinkedList.Head
Else
Copy LinkedList.Head to Probe
i=0
While i < index-1 And end of list not reached
Copy Probe.NextNode to Probe
Increment i
End While
Copy Probe.NextNode to NewNode.NextNode
Copy NewNode to Probe.NextNode
End If
End If
Set NewNode to NULL
Set Probe to NULL
Sorted lists
Lists can be designed to be maintained in a given order. In this
case, the Add method will search for the correct place in
the list to insert a new data item.
List Implementation
List Implementation in Java
The Java Collections Framework in the most recent
version of Java now includes list classes.
As you did for the stack & queue, you will create
your own List class in order to learn how a list is
implemented.
Your class will again be a bit simpler than the
Collections Framework one but it will do essentially
the same job
In this case you will look at Java implementations of
an ArrayList and a LinkedList. Both lists have the
same operations, so we can define a class List
which includes minimal implementations of the
operations. The ArrayList and LinkedList classes
will be subclasses of List.
The List class will define the set of operations which
a list class must have. This is sometimes known as
the interface of a list. Both kinds of list will have the
same interface.
List Implementation in Java