SlideShare uma empresa Scribd logo
1 de 37
Linked Lists
Towards Dynamic Data Structures 
 Array is a collection of homogeneous 
elements which are stored at consecutive 
locations 
 Main limitations of arrays: 
 It is a static data structure 
 Its size must be known at compilation time, in 
most programming languages 
 Inefficient insertion and deletion of elements 
 A dynamic data structure can overcome these 
problems
What is a Dynamic Data Structure? 
 A data structure that can shrink or grow 
during program execution 
 The size of a dynamic data structure is not 
necessarily known at compilation time, in most 
programming languages 
 Efficient insertion and deletion of elements 
 The data in a dynamic data structure can be stored 
in non-contiguous (arbitrary) locations 
 Linked list is an example of a dynamic data 
structure
What is a Linked List? 
 A linked list is a collection of nodes, each node holding 
some information and a pointer to another node in the list 
 In the following example, there are four nodes, which 
are not stored at consecutive locations 
25 
30 
40 ! 
Information 
part 
Pointer 
(Address part) 
400 
600 
300 
100 
80
Advantages of linked list 
 Unused locations in array is often a wastage of 
space 
 Linked lists offer an efficient use of memory 
 Create nodes when they are required 
 Delete nodes when they are not required anymore 
 We don’t have to know in advance how long the list 
should be
Singly Linked Lists 
• In the previous sections, we presented the array data structure and 
discussed some of its applications. 
• Arrays are nice and simple for storing things in a certain order. 
• But they have the drawback of not being very adaptable, since we have to 
fix the size N of the array in advance. 
• A linked list: 
is a collection of nodes that together form a linear ordering. 
The ordering is determined as in the children's 
game "Follow the Leader," in that each node 
is an object that stores a reference to 
an element and a reference, called next, 
to another node. 
6
Singly Linked Lists 
7 
 A singly linked list is a concrete 
data structure consisting of a 
sequence of nodes 
 Each node stores 
 element 
 link to the next node 
next 
elem node 
A B C D 
Æ
Singly Linked Lists 
8 
Figure 3.10: Example of a singly linked list whose elements are strings indicating 
airport codes. The next pointers of each node are shown as arrows. The null object is 
denoted as ∅.
Singly Linked Lists 
• A node reference another node, the next reference inside a node is a link 
or pointer to another node. 
• Moving from one node to another by following a next reference is known 
as link hopping or pointer hopping. 
• The first and last node of a linked list usually are called the head and tail 
of the list, respectively. 
• Thus, we can link hop through the list starting at the head and ending at 
the tail. 
• We can identify the tail as the node having a null next reference, which 
indicates the end of the list. 
• A linked list defined in this way is known as a singly linked list. 
9
Singly Linked Lists 
• Like an array, 
– a singly linked list keeps its elements in a certain order. 
– This order is determined by the chain of next links going from each 
node to its successor in the list. 
• Unlike an array, 
– a singly linked list does not have a predetermined fixed size, 
– and uses space proportional to the number of its elements. 
– Likewise, we do not keep track of any index numbers for the nodes in 
a linked list. 
– So we cannot tell just by examining a node if it is the second, fifth, or 
twentieth node in the list. 
10
Implementing a Singly Linked List 
• To implement a singly linked list, we define a Node class, which specifies the type of objects 
stored at the nodes of the list. Here we assume elements are character strings. 
11
Implementing a Singly Linked List 
Given the Node class, we can define a class, SLinkedList, defining the actual linked list. This class 
keeps a reference to the head node and a variable counting the total number of nodes. 
12
Insertion in a Singly Linked List 
• When using a singly linked list, we can easily insert an element at the head of the list. 
• The main idea is: 
– create a new node, 
– set its next link to refer to the same object as head, 
– and then set head to point to the new node. 
13
Insertion in a Singly Linked List 
Code Fragment 3.14: Inserting a new node v at the beginning of a singly linked list. Note that this 
method works even if the list is empty. Note that we set the next pointer for the new node v 
before we make variable head point to v. 
14
Inserting an Element at the Tail of a Singly 
Linked List 
• We can also easily insert an element at the tail of the list, provided we keep a reference to 
the tail node, as shown in Figure 3.12. 
• In this case, 
– we create a new node, 
– assign its next reference to point to the null object, 
– set the next reference of the tail to point to this new object, 
– and then assign the tail reference itself to this new node. 
15
Inserting an Element at the Tail of a Singly 
Linked List 
Code Fragment 3.15: Inserting a new node at the end of a singly linked list. This method works 
also if the list is empty. Note that we set the next pointer for the old tail node before we 
make variable tail point to the new node. 
16
Quiz’ (one possible) solution 
add_element(head, v){ // head is the head of sorted_list, v is the value to be added 
Node p, q, ptr; // we assume that the Node class exist 
ptr = new Node(v, null); 
if (v >= head.getElement()){ 
ptr.setNext(head); 
head = ptr; 
size++; 
} 
else{ 
p = head; 
q.setNext(head.getNext()); 
while (v <= q.getElement() && q.getNext() != null){ 
p.setNext(q.getNext()); 
q.setNext(q.getNext()); 
} //end while 
p.setNext(ptr); 
ptr.setNext(q); 
size++; 
}// end else 
}// end method 17
Removing an Element in a Singly Linked List 
The reverse operation of inserting a new element at the head of a linked list is to remove an 
element at the head. 
Figure 3.13: Removal of an element at the head of a singly linked list: 
(a) before the removal; 
(b) "linking out" the old new node; 
(c) after the removal. 
18
Removing an Element in a Singly Linked List 
Code Fragment 3.16: Removing the node at the beginning of a singly linked list. 
19
Removing an Element in a Singly Linked List 
• Unfortunately, we cannot easily delete the tail node of a singly linked list. Even if we have a 
tail reference directly to the last node of the list, 
– we must be able to access the node before the last node in order to remove the last node. 
– But we cannot reach the node before the tail by following next links from the tail. 
– The only way to access this node is to start from the head of the list and search all the way 
through the list. 
– But such a sequence of link hopping operations could take a long time. 
20
Doubly Linked Lists 
• As we saw in the previous section, removing an element at the tail of a singly 
linked list is not easy. 
• Indeed, it is time consuming to remove any node other than the head in a singly 
linked list, since we do not have a quick way of accessing the node in front of the 
one we want to remove. 
• Indeed, there are many applications where we do not have quick access to such a 
predecessor node. 
• For such applications, it would be nice to have a way of going both directions in a 
linked list. 
• There is a type of linked list that allows us to go in both directions 
– —forward 
– and reverse—in a linked list. 
• It is the doubly linked list. 
• Such lists allow for 
– a great variety of quick update operations, including insertion and removal at both ends, 
and in the middle. 
• A node in a doubly linked list stores two references 
– —a next link, which points to the next node in the list, 
– and a prev link, which points to the previous node in the list. 
21
Doubly Linked Lists 
22
Doubly Linked Lists 
Header and Trailer Sentinels 
• To simplify programming, 
– it is convenient to add special nodes at both ends of a 
doubly linked list: 
• a header node just before the head of the list, 
• and a trailer node just after the tail of the list. 
• These "dummy" or sentinel nodes do not store any elements. 
• The header has a valid next reference but a null prev reference, 
• while the trailer has a valid prev reference but a null next 
reference. 
– A doubly linked list with these sentinels is shown in Figure 
3.14. Note that a linked list object would simply need to 
store references to these two sentinels and a size counter 
that keeps track of the number of elements (not counting 
sentinels) in the list. 
23
Doubly Linked Lists 
Figure 3.14: A doubly linked list with sentinels, header and trailer, marking the ends of the list. An empty 
list would have these sentinels pointing to each other. We do not show the null prev pointer for the 
header nor do we show the null next pointer for the trailer. 
24
Doubly Linked Lists 
• Inserting or removing elements at either end of a doubly linked list is straight-forward 
to do. 
• Indeed, the prev links eliminate the need to traverse the list to get to the 
node just before the tail. 
Figure 3.15: Removing the node at the end of a a doubly linked list with 
header and trailer sentinels: (a) before deleting at the tail; (b) deleting at the 
tail; (c) after the deletion. 
25
Doubly Linked Lists 
Code Fragment 3.18: Removing the last node of a doubly linked list. Variable size keeps track of the 
current number of elements in the list. Note that this method works also if the list has size one. 
26
Doubly Linked Lists 
• Likewise, we can easily perform an insertion of a new element at the 
beginning of a doubly linked list. 
• Figure 3.16: Adding an element at the front: (a) 
during; (b) after. 
27
Doubly Linked Lists 
Code Fragment 3.19: Inserting a new node v at the beginning of a doubly 
linked list. Variable size keeps track of the current number of elements in the 
list. Note that this method works also on an empty list. 
28
Insertion in the Middle of a Doubly Linked List 
• Given a node v of a doubly linked list (which could be possibly the header 
but not the trailer), we can easily insert a new node z immediately after v. 
Specifically, let w the node following v. We execute the following steps: 
1. make z's prev link refer to v 
2. make z's next link refer to w 
3. make w's prev link refer to z 
4. make v's next link refer to z 
Code Fragment 3.20: Inserting a new node z after a given node v in a 
doubly linked list. 
29
Insertion in the Middle of a Doubly Linked 
List 
Figure 3.17: Adding a new node after the node storing JFK: (a) creating a 
new node with element BWI and linking it in; (b) after the insertion. 
30
Removal in the Middle of a Doubly Linked List 
• It is easy to remove a node v in the middle of a doubly linked list. 
• We access the nodes u and w on either side of v using v's getPrev and getNext 
methods (these nodes must exist, since we are using sentinels). 
• To remove node v, we simply have u and w point to each other instead of to v. We 
refer to this operation as the linking out of v. 
• We also null out v's prev and next pointers so as not to retain old references into 
the list. 
31
Removal in the Middle of a Doubly Linked List 
Code Fragment 3.21: Removing a node v in a doubly linked list. This method works even if v is 
the first, last, or only nonsentinel node. 
32
Removal in the Middle of a Doubly Linked List 
Figure 3.18: Removing the node storing PVD: (a) before the removal; (b) linking out the 
old node; (c) after the removal (and garbage collection). 
33
Circularly Linked Lists 
• A circularly linked list has the same kind of nodes as a singly linked list. 
• Each node in a circularly linked list has a next pointer and a reference to an element. 
• But there is no head or tail in a circularly linked list. 
• For instead of having the last node's next pointer be null, 
– in a circularly linked list, it points back to the first node. 
– Thus, there is no first or last node. 
– If we traverse the nodes of a circularly linked list from any node by following next pointers, 
we will cycle through the nodes. 
• Even though a circularly linked list has no beginning or end, 
– but we need some node to be marked as a special node, which we call the cursor. 
• The cursor node allows us to have a place to start from if we ever need to traverse a circularly 
linked list. 
• And if we remember this starting point, then we can also know when we are done-we are done 
with a traversal of a circularly linked list when we return to the node that was the cursor node 
when we started. 
34
Circularly Linked Lists 
By using cursor node, we can then define some simple update methods for a circularly linked list: 
• add(v): Insert a new node v immediately after the cursor; if the list is empty, then v 
becomes the cursor and its next pointer points to itself. 
• remove(): Remove and return the node v immediately after the cursor (not the cursor 
itself, unless it is the only node); if the list becomes empty, the cursor is set to null. 
• advance(): Advance the cursor to the next node in the list. 
35
Circularly Linked Lists 
• Code Fragment 3.25: A circularly linked list class with simple nodes 
36
Circularly Linked Lists 
Some Observations about the CircleList Class 
• There are a few observations we can make about the CircleList class. 
• It is a simple program that can provide enough functionality to simulate circle games, like 
Duck, Duck, Goose. I 
• t is not a robust program, however. In particular, if a circle list is empty, then calling advance 
or remove on that list will cause an exception. (Which one?) Exercise R-3.5 deals with this 
exception-generating behavior and ways of handling this empty-list condition better. 
• Explain what has been done to solve this exception? 
Sorting a Linked List 
Write the algorithm “Code Fragment 3.27” in JAVA and shows the the circularly linked 
list items before sorting and after sorting. 
37

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
stack presentation
stack presentationstack presentation
stack presentation
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Data structures
Data structuresData structures
Data structures
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Linked List
Linked ListLinked List
Linked List
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
 
linked list
linked list linked list
linked list
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
BCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHIBCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHI
 
single linked list
single linked listsingle linked list
single linked list
 
Circular queue
Circular queueCircular queue
Circular queue
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Doubly linked list
Doubly linked listDoubly linked list
Doubly linked list
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structures
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 

Semelhante a Data Structures- Part7 linked lists

Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
FaheemMahmood2
 

Semelhante a Data Structures- Part7 linked lists (20)

Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Linked list (1).pptx
Linked list (1).pptxLinked list (1).pptx
Linked list (1).pptx
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdf
 
Linked lists
Linked listsLinked lists
Linked lists
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
data structures and applications power p
data structures and applications power pdata structures and applications power p
data structures and applications power p
 
Linked List
Linked ListLinked List
Linked List
 
1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
 
linked list using c
linked list using clinked list using c
linked list using c
 
csc211_lecture_21.pptx
csc211_lecture_21.pptxcsc211_lecture_21.pptx
csc211_lecture_21.pptx
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptx
 
Linked list
Linked listLinked list
Linked list
 
DATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxDATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptx
 
DATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptxDATA STRUCTURES AND LINKED LISTS IN C.pptx
DATA STRUCTURES AND LINKED LISTS IN C.pptx
 
Linked list.docx
Linked list.docxLinked list.docx
Linked list.docx
 
Linked list
Linked listLinked list
Linked list
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 

Mais de Abdullah Al-hazmy (7)

Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Data Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithmsData Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithms
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplified
 
Data Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queuesData Structures- Part8 stacks and queues
Data Structures- Part8 stacks and queues
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Último (20)

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 

Data Structures- Part7 linked lists

  • 2. Towards Dynamic Data Structures  Array is a collection of homogeneous elements which are stored at consecutive locations  Main limitations of arrays:  It is a static data structure  Its size must be known at compilation time, in most programming languages  Inefficient insertion and deletion of elements  A dynamic data structure can overcome these problems
  • 3. What is a Dynamic Data Structure?  A data structure that can shrink or grow during program execution  The size of a dynamic data structure is not necessarily known at compilation time, in most programming languages  Efficient insertion and deletion of elements  The data in a dynamic data structure can be stored in non-contiguous (arbitrary) locations  Linked list is an example of a dynamic data structure
  • 4. What is a Linked List?  A linked list is a collection of nodes, each node holding some information and a pointer to another node in the list  In the following example, there are four nodes, which are not stored at consecutive locations 25 30 40 ! Information part Pointer (Address part) 400 600 300 100 80
  • 5. Advantages of linked list  Unused locations in array is often a wastage of space  Linked lists offer an efficient use of memory  Create nodes when they are required  Delete nodes when they are not required anymore  We don’t have to know in advance how long the list should be
  • 6. Singly Linked Lists • In the previous sections, we presented the array data structure and discussed some of its applications. • Arrays are nice and simple for storing things in a certain order. • But they have the drawback of not being very adaptable, since we have to fix the size N of the array in advance. • A linked list: is a collection of nodes that together form a linear ordering. The ordering is determined as in the children's game "Follow the Leader," in that each node is an object that stores a reference to an element and a reference, called next, to another node. 6
  • 7. Singly Linked Lists 7  A singly linked list is a concrete data structure consisting of a sequence of nodes  Each node stores  element  link to the next node next elem node A B C D Æ
  • 8. Singly Linked Lists 8 Figure 3.10: Example of a singly linked list whose elements are strings indicating airport codes. The next pointers of each node are shown as arrows. The null object is denoted as ∅.
  • 9. Singly Linked Lists • A node reference another node, the next reference inside a node is a link or pointer to another node. • Moving from one node to another by following a next reference is known as link hopping or pointer hopping. • The first and last node of a linked list usually are called the head and tail of the list, respectively. • Thus, we can link hop through the list starting at the head and ending at the tail. • We can identify the tail as the node having a null next reference, which indicates the end of the list. • A linked list defined in this way is known as a singly linked list. 9
  • 10. Singly Linked Lists • Like an array, – a singly linked list keeps its elements in a certain order. – This order is determined by the chain of next links going from each node to its successor in the list. • Unlike an array, – a singly linked list does not have a predetermined fixed size, – and uses space proportional to the number of its elements. – Likewise, we do not keep track of any index numbers for the nodes in a linked list. – So we cannot tell just by examining a node if it is the second, fifth, or twentieth node in the list. 10
  • 11. Implementing a Singly Linked List • To implement a singly linked list, we define a Node class, which specifies the type of objects stored at the nodes of the list. Here we assume elements are character strings. 11
  • 12. Implementing a Singly Linked List Given the Node class, we can define a class, SLinkedList, defining the actual linked list. This class keeps a reference to the head node and a variable counting the total number of nodes. 12
  • 13. Insertion in a Singly Linked List • When using a singly linked list, we can easily insert an element at the head of the list. • The main idea is: – create a new node, – set its next link to refer to the same object as head, – and then set head to point to the new node. 13
  • 14. Insertion in a Singly Linked List Code Fragment 3.14: Inserting a new node v at the beginning of a singly linked list. Note that this method works even if the list is empty. Note that we set the next pointer for the new node v before we make variable head point to v. 14
  • 15. Inserting an Element at the Tail of a Singly Linked List • We can also easily insert an element at the tail of the list, provided we keep a reference to the tail node, as shown in Figure 3.12. • In this case, – we create a new node, – assign its next reference to point to the null object, – set the next reference of the tail to point to this new object, – and then assign the tail reference itself to this new node. 15
  • 16. Inserting an Element at the Tail of a Singly Linked List Code Fragment 3.15: Inserting a new node at the end of a singly linked list. This method works also if the list is empty. Note that we set the next pointer for the old tail node before we make variable tail point to the new node. 16
  • 17. Quiz’ (one possible) solution add_element(head, v){ // head is the head of sorted_list, v is the value to be added Node p, q, ptr; // we assume that the Node class exist ptr = new Node(v, null); if (v >= head.getElement()){ ptr.setNext(head); head = ptr; size++; } else{ p = head; q.setNext(head.getNext()); while (v <= q.getElement() && q.getNext() != null){ p.setNext(q.getNext()); q.setNext(q.getNext()); } //end while p.setNext(ptr); ptr.setNext(q); size++; }// end else }// end method 17
  • 18. Removing an Element in a Singly Linked List The reverse operation of inserting a new element at the head of a linked list is to remove an element at the head. Figure 3.13: Removal of an element at the head of a singly linked list: (a) before the removal; (b) "linking out" the old new node; (c) after the removal. 18
  • 19. Removing an Element in a Singly Linked List Code Fragment 3.16: Removing the node at the beginning of a singly linked list. 19
  • 20. Removing an Element in a Singly Linked List • Unfortunately, we cannot easily delete the tail node of a singly linked list. Even if we have a tail reference directly to the last node of the list, – we must be able to access the node before the last node in order to remove the last node. – But we cannot reach the node before the tail by following next links from the tail. – The only way to access this node is to start from the head of the list and search all the way through the list. – But such a sequence of link hopping operations could take a long time. 20
  • 21. Doubly Linked Lists • As we saw in the previous section, removing an element at the tail of a singly linked list is not easy. • Indeed, it is time consuming to remove any node other than the head in a singly linked list, since we do not have a quick way of accessing the node in front of the one we want to remove. • Indeed, there are many applications where we do not have quick access to such a predecessor node. • For such applications, it would be nice to have a way of going both directions in a linked list. • There is a type of linked list that allows us to go in both directions – —forward – and reverse—in a linked list. • It is the doubly linked list. • Such lists allow for – a great variety of quick update operations, including insertion and removal at both ends, and in the middle. • A node in a doubly linked list stores two references – —a next link, which points to the next node in the list, – and a prev link, which points to the previous node in the list. 21
  • 23. Doubly Linked Lists Header and Trailer Sentinels • To simplify programming, – it is convenient to add special nodes at both ends of a doubly linked list: • a header node just before the head of the list, • and a trailer node just after the tail of the list. • These "dummy" or sentinel nodes do not store any elements. • The header has a valid next reference but a null prev reference, • while the trailer has a valid prev reference but a null next reference. – A doubly linked list with these sentinels is shown in Figure 3.14. Note that a linked list object would simply need to store references to these two sentinels and a size counter that keeps track of the number of elements (not counting sentinels) in the list. 23
  • 24. Doubly Linked Lists Figure 3.14: A doubly linked list with sentinels, header and trailer, marking the ends of the list. An empty list would have these sentinels pointing to each other. We do not show the null prev pointer for the header nor do we show the null next pointer for the trailer. 24
  • 25. Doubly Linked Lists • Inserting or removing elements at either end of a doubly linked list is straight-forward to do. • Indeed, the prev links eliminate the need to traverse the list to get to the node just before the tail. Figure 3.15: Removing the node at the end of a a doubly linked list with header and trailer sentinels: (a) before deleting at the tail; (b) deleting at the tail; (c) after the deletion. 25
  • 26. Doubly Linked Lists Code Fragment 3.18: Removing the last node of a doubly linked list. Variable size keeps track of the current number of elements in the list. Note that this method works also if the list has size one. 26
  • 27. Doubly Linked Lists • Likewise, we can easily perform an insertion of a new element at the beginning of a doubly linked list. • Figure 3.16: Adding an element at the front: (a) during; (b) after. 27
  • 28. Doubly Linked Lists Code Fragment 3.19: Inserting a new node v at the beginning of a doubly linked list. Variable size keeps track of the current number of elements in the list. Note that this method works also on an empty list. 28
  • 29. Insertion in the Middle of a Doubly Linked List • Given a node v of a doubly linked list (which could be possibly the header but not the trailer), we can easily insert a new node z immediately after v. Specifically, let w the node following v. We execute the following steps: 1. make z's prev link refer to v 2. make z's next link refer to w 3. make w's prev link refer to z 4. make v's next link refer to z Code Fragment 3.20: Inserting a new node z after a given node v in a doubly linked list. 29
  • 30. Insertion in the Middle of a Doubly Linked List Figure 3.17: Adding a new node after the node storing JFK: (a) creating a new node with element BWI and linking it in; (b) after the insertion. 30
  • 31. Removal in the Middle of a Doubly Linked List • It is easy to remove a node v in the middle of a doubly linked list. • We access the nodes u and w on either side of v using v's getPrev and getNext methods (these nodes must exist, since we are using sentinels). • To remove node v, we simply have u and w point to each other instead of to v. We refer to this operation as the linking out of v. • We also null out v's prev and next pointers so as not to retain old references into the list. 31
  • 32. Removal in the Middle of a Doubly Linked List Code Fragment 3.21: Removing a node v in a doubly linked list. This method works even if v is the first, last, or only nonsentinel node. 32
  • 33. Removal in the Middle of a Doubly Linked List Figure 3.18: Removing the node storing PVD: (a) before the removal; (b) linking out the old node; (c) after the removal (and garbage collection). 33
  • 34. Circularly Linked Lists • A circularly linked list has the same kind of nodes as a singly linked list. • Each node in a circularly linked list has a next pointer and a reference to an element. • But there is no head or tail in a circularly linked list. • For instead of having the last node's next pointer be null, – in a circularly linked list, it points back to the first node. – Thus, there is no first or last node. – If we traverse the nodes of a circularly linked list from any node by following next pointers, we will cycle through the nodes. • Even though a circularly linked list has no beginning or end, – but we need some node to be marked as a special node, which we call the cursor. • The cursor node allows us to have a place to start from if we ever need to traverse a circularly linked list. • And if we remember this starting point, then we can also know when we are done-we are done with a traversal of a circularly linked list when we return to the node that was the cursor node when we started. 34
  • 35. Circularly Linked Lists By using cursor node, we can then define some simple update methods for a circularly linked list: • add(v): Insert a new node v immediately after the cursor; if the list is empty, then v becomes the cursor and its next pointer points to itself. • remove(): Remove and return the node v immediately after the cursor (not the cursor itself, unless it is the only node); if the list becomes empty, the cursor is set to null. • advance(): Advance the cursor to the next node in the list. 35
  • 36. Circularly Linked Lists • Code Fragment 3.25: A circularly linked list class with simple nodes 36
  • 37. Circularly Linked Lists Some Observations about the CircleList Class • There are a few observations we can make about the CircleList class. • It is a simple program that can provide enough functionality to simulate circle games, like Duck, Duck, Goose. I • t is not a robust program, however. In particular, if a circle list is empty, then calling advance or remove on that list will cause an exception. (Which one?) Exercise R-3.5 deals with this exception-generating behavior and ways of handling this empty-list condition better. • Explain what has been done to solve this exception? Sorting a Linked List Write the algorithm “Code Fragment 3.27” in JAVA and shows the the circularly linked list items before sorting and after sorting. 37