Você está na página 1de 29

Chapter 66

Chapter
Data Structures:
Structures: Linked
Linked Lists
Lists
Data

CSC 113
King Saud University
College of Computer and Information Sciences
Department of Computer Science

Dr. S. HAMMAMI

1. Objectives
After you have read and studied this chapter, you should be able to:
Understandthe
theconcept
conceptof
ofaadynamic
dynamicdata
datastructure.
structure.
Understand
Beable
ableto
tocreate
createand
anduse
usedynamic
dynamicdata
datastructures
structuressuch
suchas
aslinked
linked
Be
lists.
lists.
Understandthe
thestack
stackand
andqueue
queueADTs.
ADTs.
Understand
Variousimportant
importantapplications
applicationsof
oflinked
linkeddata
datastructures.
structures.
Various
Knowhow
howto
touse
useinheritance
inheritanceto
todefine
define extensible
extensibledata
data
Know
structures.
structures.
Createreusable
reusabledata
datastructures
structureswith
withclasses,
classes,inheritance
inheritanceand
and
Create
composition.
composition.
Dr. Salah Hammami

KSU-CCIS-CS

2. Self-Referential Classes: Definition

Self-referential class
Contains an instance variable that refers to another
object of the same class type

That instance variable is called a link

A null reference indicates that the link does not


refer to another object

Dr. Salah Hammami

KSU-CCIS-CS

2. Self-Referential Classes (cont)

A link to another
Node object.
T

Node<T>
T
Node<T>
Node (in o: T)
setData(in o: T)
getData(): T
setNext(in link: Node<T>)
getNext(): Node<T>

1
1
next

data
Node<T>

Node (in o: T)
setData(in o: T)
getData(): T
setNext(in link:
Node<T>)
getNext():
Node<T>
Dr. Salah Hammami

KSU-CCIS-CS

Basic Node: The Generic Node Class

A node in a linked list contains data elements and link elements.


Student

- name: String
- id: int
- grade: double
Node<T>
T
Node<T>

+ student()
+ set()

Node (in o: T)
setData(in o: T)
getData(): T
setNext(in link: Node<T>)
getNext(): Node<T>

+ get()

Ali

Dr. Salah Hammami

Jamel

Kamal

KSU-CCIS-CS

Generic Node Class: Implementation


public class Node<T> {
private T data; // Stores any kind of data
private Node<T> next;
public Node<T>(T obj) {
data = obj;
next = null;
}
public void setNext( Node<T> nextPtr ) {
next = nextPtr;
}
public Node<T> getNext() {
return next;
}
public void setData(T obj) {
data = obj;
}
public T getData() {
return data;
}
public String toString() {
return data.toString();
}
}
Dr. Salah Hammami

KSU-CCIS-CS

Connecting two nodes


Thestatements
statements
The

StudentS1
S1==new
newStudent(Ali,
Student(Ali,42700000,
42700000,3.5)
3.5)
Student
StudentS2
S2==new
newStudent(Ahmed,
Student(Ahmed,4271000,
4271000,3.9)
3.9)
Student
Node <Student>
<Student> pp == new
new Node
Node <Student>(S1);
<Student>(S1);
Node
Node <Student>
<Student> qq == new
new Node(S2);
Node(S2);
Node
allocate storage
storage for
for two
two objects
objects of
of type
typeNode
Node referenced
referenced by
by pp and
and qq. .
allocate
storesthe
theobject
objectS1
S1, ,and
andthe
thenode
nodereferenced
referenced
Thenode
nodereferenced
referencedby
byppstores
The
storesthe
theobject
objectS2
S2. .The
Thenext
nextfields
fieldsof
ofboth
bothnodes
nodesare
arenull
null. .
byqqstores
by

Nodes referenced by p and q

S1

Dr. Salah Hammami

S2

KSU-CCIS-CS

Connecting two nodes (Cont)


Thestatement
statement
The
p.setNext(q);
(q);
p.setNext

storesthe
theaddress
addressof
ofnode
nodeqqininthe
thelink
linkfield
fieldof
ofnode
nodepp, ,thereby
thereby
stores
nodeqq, ,and
andforming
formingaalinked
linkedlist
listwith
with22nodes.
nodes.
connectingnode
nodepptotonode
connecting
nextfield
fieldof
ofthe
thesecond
secondlist
listnode
nodeindicates
indicatesthe
the
Thediagonal
diagonalline
lineininthe
thenext
The
valuenull
null. .
value
Linked list with two nodes

S1

Dr. Salah Hammami

S2

KSU-CCIS-CS

Linked Lists: Definition


Linkedlist
list
Linked
Linearcollection
collectionof
ofnodes
nodes
Linear
linkedlist
listisisbased
basedon
onthe
theconcept
conceptof
ofaaself-referential
self-referentialobject
object--- AAlinked
anobject
objectthat
thatrefers
referstotoan
anobject
objectof
ofthe
thesame
sameclass.
class.
an
programtypically
typicallyaccesses
accessesaalinked
linkedlist
listvia
viaaareference
referencetotothe
thefirst
first
AAprogram
nodeininthe
thelist
list
node
programaccesses
accesseseach
eachsubsequent
subsequentnode
nodevia
viathe
thelink
linkreference
reference
AAprogram
storedininthe
theprevious
previousnode
node
stored
Aredynamic
dynamic
Are
Thelength
lengthof
ofaalist
listcan
canincrease
increaseor
ordecrease
decreaseas
asnecessary
necessary
The
Becomefull
fullonly
onlywhen
whenthe
thesystem
systemhas
hasinsufficient
insufficientmemory
memorytoto
Become
satisfydynamic
dynamicstorage
storageallocation
allocationrequests
requests
satisfy
Dr. Salah Hammami

KSU-CCIS-CS

Generic Linked Lists

List<T>
T

name: String
List ()
1
data

1
next

List(n: String)
insertAtFront(o: T)

Node<T>

insertAtBack(o: T)
Node (in o: T)
setData(in o: T)
getData(): T
setNext(in link:
Node<T>)
getNext():
Node<T>

first

removeFromFront():T
removeFromBack():T
isEmpty(): Boolean
size(): int
insertAfter(int, T)
insertBefore(int, T)
remove(int):T

Dr. Salah Hammami

KSU-CCIS-CS

Implementation of the Generic Linked Lists


public class List<T>
{

private Node<T> first;


private String name;

public List()
{ name= ;
first=null;
}

public List(String listName )


{ name = listName;
first = null;
}

}
Dr. Salah Hammami

KSU-CCIS-CS

Linked List: insertAtFront


MethodinsertAtFronts
insertAtFrontssteps
steps
Method
CallisEmpty
isEmptytotodetermine
determinewhether
whetherthe
thelist
listisisempty
empty
Call
thelist
listisisempty,
empty,assign
assignfirstNode
firstNodeand
andlastNode
lastNodetotothe
thenew
newListNode
ListNodethat
thatwas
was
IfIfthe
initializedwith
withinsertItem
insertItem
initialized
TheListNode
ListNodeconstructor
constructorcall
callsets
setsdata
datatotorefer
refertotothe
theinsertItem
insertItempassed
passedas
as
The
anargument
argumentand
andsets
setsreference
referencenextNode
nextNodetotonull
null
an
thelist
listisisnot
notempty,
empty,set
setfirstNode
firstNodetotoaanew
newListNode
ListNodeobject
objectand
andinitialize
initializethat
that
IfIfthe
objectwith
withinsertItem
insertItemand
andfirstNode
firstNode
object
TheListNode
ListNodeconstructor
constructorcall
callsets
setsdata
datatotorefer
refertotothe
theinsertItem
insertItempassed
passedas
as
The
anargument
argumentand
andsets
setsreference
referencenextNode
nextNodetotothe
theListNode
ListNodepassed
passedas
as
an
argument,which
whichpreviously
previouslywas
wasthe
thefirst
firstnode
node
argument,
Dr. Salah Hammami

KSU-CCIS-CS

Linked List: insertAtFront (Cont)


Graphical representation of operation insertAtFront

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: insertAtFront (Cont)


Code of insertAtFront

public void
void insertAtFront(T
insertAtFront(T obj)
obj) {{
public
Node NN == new
new Node(obj);
Node(obj);
Node
N.setNext(first);
N.setNext(first);
first == N;
N;
first
// insertAtFront()
insertAtFront()
}} //

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: insertAtBack


MethodinsertAtBacks
insertAtBackssteps
steps
Method
CallisEmpty
isEmptytotodetermine
determinewhether
whetherthe
thelist
listisisempty
empty
Call
thelist
listisisempty,
empty,assign
assignfirstNode
firstNodeand
andlastNode
lastNodetotothe
thenew
newListNode
ListNodethat
that
IfIfthe
wasinitialized
initializedwith
withinsertItem
insertItem
was
TheListNode
ListNodeconstructor
constructorcall
callsets
setsdata
datatotorefer
refertotothe
theinsertItem
insertItempassed
passed
The
asan
anargument
argumentand
andsets
setsreference
referencenextNode
nextNodetotonull
null
as
thelist
listisisnot
notempty,
empty,assign
assigntotolastNode
lastNodeand
andlastNode.nextNode
lastNode.nextNodethe
the
IfIfthe
referencetotothe
thenew
newListNode
ListNodethat
thatwas
wasinitialized
initializedwith
withinsertItem
insertItem
reference
TheListNode
ListNodeconstructor
constructorsets
setsdata
datatotorefer
refertotothe
theinsertItem
insertItempassed
passedas
asan
an
The
argumentand
andsets
setsreference
referencenextNode
nextNodetotonull
null
argument

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: insertAtBack (Cont)


Graphical representation of operation insertAtBack.

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: insertAtBack (Cont)


public void
void insertAtBack(T
insertAtBack(T obj)
obj) {{
public
if (isEmpty())
(isEmpty())
if

Solution 1

first == new
new Node(obj);
Node(obj);
first
else {{
else
Node current
current == first;
first;
Node
while (current.getNext()
(current.getNext() !=
!= null)
null)
while
current == current.getNext();
current.getNext();
current
current.setNext(new Node(obj));
Node(obj));
current.setNext(new

// Start
Start at
at head
head of
of list
list
//
// Find
Find the
the end
end of
of the
the list
list
//
// Insert
Insert the
the newObj
newObj
//

}}
// insertAtRear
insertAtRear
}} //
public void
void insertAtBack(T
insertAtBack(T obj)
obj) {{
public
Node NN =new
=new Node(obj);
Node(obj);
Node

Solution 2

if (isEmpty())
(isEmpty())
if
first == N;
N;
first
else {{
else
Node current
current == first;
first;
Node
while (current.getNext()
(current.getNext() !=
!= null)
null)
while
current == current.getNext();
current.getNext();
current
current.setNext(N));
current.setNext(N));

// Start
Start at
at head
head of
of list
list
//
// Find
Find the
the end
end of
of the
the list
list
//

// Insert
Insert the
the newObj
newObj
//

}}
// insertAtRear
insertAtRear
}} //

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: removeFromFront

MethodremoveFromFronts
removeFromFrontssteps
steps
Method
Throwan
anEmptyListException
EmptyListExceptionififthe
thelist
listisisempty
empty
Throw
AssignfirstNode.data
firstNode.datatotoreference
referenceremovedItem
removedItem
Assign
firstNodeand
andlastNode
lastNoderefer
refertotothe
thesame
sameobject,
object,set
setfirstNode
firstNodeand
and
IfIffirstNode
lastNodetotonull
null
lastNode
thelist
listhas
hasmore
morethan
thanone
onenode,
node,assign
assignthe
thevalue
valueof
offirstNode.nextNode
firstNode.nextNodetoto
IfIfthe
firstNode
firstNode
Returnthe
theremovedItem
removedItemreference
reference
Return

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: removeFromFront

Graphical representation of operation removeFromFront.


Dr. Salah Hammami

KSU-CCIS-CS

Linked List: removeFromFront

Code of removeFromFront

public TT removeFromFrontt()
removeFromFrontt() {{
public
if (isEmpty())
(isEmpty())
if
return null;
null;
return
Node NN == first;
first; //
// TT dd == first.getdata();
first.getdata();
Node
first == first.getNext();
first.getNext();
first
return N.getData();
N.getData(); //
// return
return d;
d;
return
}}

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: removeFromBack


MethodremoveFromBacks
removeFromBackssteps
steps
Method
Throwsan
anEmptyListException
EmptyListExceptionififthe
thelist
listisisempty
empty
Throws
AssignlastNode.data
lastNode.datatotoremovedItem
removedItem
Assign
thefirstNode
firstNodeand
andlastNode
lastNoderefer
refertotothe
thesame
sameobject,
object,set
setfirstNode
firstNodeand
and
IfIfthe
lastNodetotonull
null
lastNode
thelist
listhas
hasmore
morethan
thanone
onenode,
node,create
createthe
theListNode
ListNodereference
referencecurrent
currentand
and
IfIfthe
assignititfirstNode
firstNode
assign
Walkthe
thelist
listwith
withcurrent
currentuntil
untilititreferences
referencesthe
thenode
nodebefore
beforethe
thelast
lastnode
node
Walk
Thewhile
whileloop
loopassigns
assignscurrent.nextNode
current.nextNodetotocurrent
currentas
aslong
longas
as
The
current.nextNodeisisnot
notlastNode
lastNode
current.nextNode
Dr. Salah Hammami

KSU-CCIS-CS

Linked List: removeFromBack


Graphical representation of operation removeFromBack.

Dr. Salah Hammami

KSU-CCIS-CS

Linked List: removeFromBack


Code of removeFromBack
public TT removeFromBack()
removeFromBack() {{
public
if (isEmpty())
(isEmpty()) //
// Empty
Empty list
list
if
return null;
null;
return
Node current
current == first;
first;
Node
if (current.getNext()
(current.getNext() ==
== null)
null) {{ //
// Singleton
Singleton list
list
if
first == null;
null;
first
return current.getData();
current.getData();
return
}}
Node previous
previous == null;
null;
// All
All other
other cases
cases
Node
//
while (current.getNext()
(current.getNext() !=
!= null)
null) {{
while
previous == current;
current;
previous
current == current.getNext();
current.getNext();
current
}}
previous.setNext(null);
previous.setNext(null);
return current.getData();
current.getData();
return
// removeLast()
removeLast()
}} //
Dr. Salah Hammami

KSU-CCIS-CS

Generic Linked Lists and Interface


List<T>

name: String

1
next

List ()

data

List(n: String)

Node<T>

Node (in o: T)
setData(in o: T)
getData(): T
setNext(in link:
Node<T>)
getNext():
Node<T>

Dr. Salah Hammami

displayAll()
1

first

countSimilar(T): int
search(T): int
remove(int): T
remove(T):T
Intersection(List<T>): List<T>

KSU-CCIS-CS

Generic Linked Lists and Interface


Code of displayAll()
public void
void displayAll()
displayAll() {{
public
if (!(isEmpty()))
(!(isEmpty()))
if
{{

<Interface>
Node current
current == first;
first;
Node
while (current!=
(current!= null)
null)
while

AAAA
display()

{{
current.getData().display()
display();;
current.getData().
current=current.getNext();
current=current.getNext();
}}
}}
}}

This method must be implemented by each substitute class of the generic type.
We add an Interface to our package containing this method display and each substitutions class of the
generic type must implement the Interface.

Dr. Salah Hammami

KSU-CCIS-CS

Generic Linked Lists and Interface


Code of countSimilar(T):int
public int
int count(T
count(T t)
t) {{
public
Node current
current == first;
first;
Node
int x=0;
x=0;
int
while (current!=
(current!= null)
null)
while
{{

<Interface>
AAAA
display()

if (current.getData().
(current.getData().compare(t))
compare(t))
if
x++;
x++;

compare(Object): Boolean

current=current.getNext();
current=current.getNext();
}}
return x;
x;
return
}}

This method must be implemented by each substitute class of the generic type.
We add an Interface to our package containing this method compare and each substitutions class of the
generic type must implement the Interface.

Dr. Salah Hammami

KSU-CCIS-CS

Generic Linked Lists and Interface


Code of search(T):int
public int
int search(T
search(T t)
t) {{
public
Node current
current == first;
first;
Node
int x=0;
x=0;
int
while (current!=
(current!= null)
null)
while
{{

<Interface>
AAAA
display()

x++;
x++;
if (current.getData().
(current.getData().compare(t))
compare(t))
if

compare(Object): Boolean

return x;
x;
return
current=current.getNext();
current=current.getNext();
}}
return -1;
-1;
return
}}

This method must be implemented by each substitute class of the generic type.
We add an Interface to our package containing this method compare and each substitutions class of the
generic type must implement the Interface.
Dr. Salah Hammami

KSU-CCIS-CS

Generic Linked Lists and Interface


Code of remove(int):T
public TT remove
remove (int
(int x)
x) {{
public
if ((isEmpty())
((isEmpty()) ||
|| (x<0)
(x<0) ||
|| (x>size())
(x>size())
if
return null;
null;
return
if (x==1)
(x==1) return
return removeFromFront();
removeFromFront();
if
(x==size())return
returnremoveFromBack();
removeFromBack();
ifif(x==size())
Node current
current == first;
first;
Node
for(int i=1,
i=1, i<x-1
i<x-1 ;; i++)
i++)
for(int
current == current.getNext();
current.getNext();
current
d=current.getNext().getdata();
TT d=current.getNext().getdata();
current.setNext(current.getNext().getNext());
current.setNext(current.getNext().getNext());
return d;
d;
return
}}

Dr. Salah Hammami

KSU-CCIS-CS

Generic Linked Lists and Interface

Code of remove(T):T

public int
int remove(T
remove(T t)
t) {{
public
int xx == search(t);
search(t);
int
return remove(x);
remove(x);
return
}}

Dr. Salah Hammami

KSU-CCIS-CS

Você também pode gostar