SlideShare a Scribd company logo
Data Structures & Algorithm
CSC-102
Lecture 2
Arrays & Link List
Lecturer: Syeda Nazia Ashraf
1
Arrays
▪ Array declaration: int x[6];
▪ An array is collection of cells of the same type.
▪ The collection has the name ‘x’.
▪ The cells are numbered with consecutive
integers.
▪ To access a cell, use the array name and an
index:
x[0], x[1], x[2], x[3], x[4], x[5]
2
Array Layout (Linear-array)
x[1]
x[2]
x[3]
x[4]
x[5]
x[0]
Array cells are
contiguous in
computer memory
The memory can be
thought of as an
array
3
Linear(1-Dimensional Array)
A linear array A[8] consisting of numbers is pictured
in following figure.
4
A linear array STUDENT consisting of the names of
six students STUDENT[1] denotes John Brown,
STUDENT[2] denotes Sandra Gold, and so on.
2-Dimensional Array
5
A chain of 28 stores, each store having 4 departments, may lists its weekly
sales first subscript denotes the store and the second subscript the
department. SALES is the name given to the Array.
SALES[1,1]=2872, SALES[1,2]=805, SALES[1,3]=3211,……..,SALES[28,4]=282
The size of this array is denoted by 28 X 4 (read 28 by 4), since it contains 28 rows
(the horizontal lines of numbers) and 4 columns (the vertical lines of numbers).
Such arrays are called Matrices in mathematics, and tables in business
applications.
Link List
6
Tree
7
8
Data Structure Operations
9
The following four operations play a major role:
1. Traversing: Accessing each record exactly once so that certain items in the
record may be processed. (this accessing and processing is sometimes called
“visiting” the record.)
2. Searching: Finding the location of the record with a given key value, or finding
the locations of all records which satisfy one or more conditions.
3. Inserting: Adding a new record to the structure.
4. Deleting: Removing a record from the structure.
Sometimes two or more of the operations may be used in a given situation; e.g.,
we may want to delete the record with a given key, which may mean we first
need to search for the location of the record.
The following operations, which are used in special situations, will also be
considered:
1. Sorting: Arranging the records in some logical order (e.g., alphabetically
according to some NAME key, or in numerical order according to some
NUMBER key, such as social security number or account number or student
id)
2. Merging: Combining the records in two different sorted files into a single
sorted file.
ADT
• An ADT, is a logical description of how we view the
data and the operations that are allowed without
regard to how they will be implemented.
• This means that we are concerned only with what the
data is representing and not with how it will
eventually be constructed.
• By providing this level of abstraction, we are creating
an encapsulation around the data. The idea is that by
encapsulating the details of the implementation, we
are hiding them from the user’s view. This is
called information hiding.
• The implementation of an abstract data type, often
referred to as a data structure, will require that we
provide a physical view of the data using some
collection of programming constructs and primitive
data types.
10
11
Figure shows a picture of what an abstract data type is and how it operates. The
user interacts with the interface, using the operations that have been specified by
the abstract data type. The abstract data type is the shell that the user interacts
with. The implementation is hidden one level deeper. The user is not concerned
with the details of the implementation.
ADT
12
Figure shows:
13
14
Data Abstraction and Abstract Data Types (ADT)
• A data type is a template for objects and a set of operations
that define the behavior of the objects ( or Instances) of that
type.
• An abstract Data Type (ADT) is a data type in which the
implementation details are hidden and the user is concerned
with the properties ( or behavior) of that type.
• An ADT has two components:
- Interface (the behavior)
- Implementation
• Example:
- int, float
15
Implementation
Abstract Data Type
• The data structures used to
implement the data type can
only be accessed through the
interface.
• Any change in the
implementation does not
change the user programs as
long as the interface remains
the same
• This is also known as the data
encapsulation or data
abstraction.
Interface 1 Interface 2
Interface 3 Interface 4
Implementation
16
17
Linked List
• A list is an abstract data type that implements an
ordered collection of values, where the same
value may occur more than once.
• Create a structure called a Node.
• The object field will hold the actual list
element.
• The next field in the structure will hold the
starting location of the next node.
• Chain the nodes together to form a linked list.
18
object next
Linked List
▪ Picture of our list (2, 6, 8, 7, 1) stored as a
linked list:
2 6 8 7 1
head
current
size=5
19
Link List
20
Linked List
Note some features of the list:
▪ Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
▪ The current here is a pointer, not an index.
▪ The next field in the last node points to nothing.
We will place the memory address NULL which
is guaranteed to be inaccessible.
21
Linked List
Actual picture in memory
1051
1052
1055
1059
1060
1061
1062
1063
1064
1056
1057
1058
1053
1054 2
6
8
7
1
1051
1063
1057
1060
0
head 1054
1063
current
1065
Tail / null
Real world examples: Linked lists
• Road train
• File blocks on disk
Real world examples: Linked lists
24
In real life, objects often appear in simple lists. For
example,Companies may maintain a list of
Employees, Banks may keep a list of Bank Accounts,
a Person may keep a list of "Things to Do".etc..
A List ADT allows us to access any of its elements
at any time as well as insert or remove elements anywhere in the list
at any time. The list will automatically shift the elements around in
memory to make the needed room or reduce the unused space. The
general list is the most flexible kind of list in terms of its capabilities.
We use a general List whenever we have elements coming in and
being removed in a random order. For example, when we have a
shelf of library books, we may need to remove a book from anywhere
on the shelf and we may insert books back into their proper location
when they are returned.
Operations on Linked List:
There are several operations associated with
linked list i.e.
a) Traversing a Linked List
Suppose we want to traverse LIST in order to
process each node exactly once. The
traversing algorithm uses a pointer variable
PTR which points to the node that is currently
being processed. Accordingly, PTR->NEXT
points to the next node to be processed so,
25
26
PTR:=START [ Moves the pointer to the first node of the
list]
PTR:=LINK[PTR] [ Moves the pointer to the next node in
the list.]
INFO[PTR] [Process information at the node]
27
28
Algorithm: (Traversing a Linked List) Let LIST be a
linked list in memory. This algorithm traverses LIST,
applying an operation PROCESS to each element of
list. The variable PTR point to the node currently
being processed.
1. Set PTR:=START. [Initializes pointer PTR.]
2. Repeat Steps 3 and 4 while PTR ≠ NULL.
3. Apply PROCESS to INFO[PTR].
4. Set PTR:= LINK[PTR]. [PTR now points to the
next node]
[End of Step 2 loop.]
5. Exit.
29
b) Searching a Linked List:(UNSORTED LIST)
Suppose the data in LIST are not necessarily sorted. Then one searches for ITEM in LIST by
traversing through the list using a pointer variable PTR and comparing ITEM with the contents
INFO[PTR] of each node, one by one, of LIST. Before we update the pointer PTR by
PTR:=LINKPTR], we require two tests. First we have to check to see whether we have reached
the end of the LIST i.e. PTR=NULL. If not, then we check to see whether INFO[PTR]=ITEM.
The two tests cannot be performed at the same time, since INFO[PTR] is not defined when
PTR=NULL. Accordingly we use the First test to control the execution of a loop, and we let the
second test take place inside the loop.
Algorithm: SEARCH(INFO, LINK,START, ITEM, LOC)
LIST is a linked list in the memory. This algorithm finds the location LOC of the
node where ITEM first appear in LIST, or sets LOC=NULL.
1. Set PTR:=START.
2. Repeat Step 3 while PTR≠NULL:
3. If ITEM = INFO[PTR], then:
Set LOC:=PTR, and Exit. [Search is successful.]
Else:
Set PTR:=LINK[PTR]. [PTR now points to the next node]
[End of If structure.]
[End of Step 2 loop.]
4. Set LOC:=NULL. [Search is unsuccessful.]
5. Exit.
30
b) Searching a Linked List:(SORTED LIST)
Suppose the data in LIST are sorted. Again we search for ITEM in LIST by traversing the list using
a pointer variable PTR and comparing ITEM with the contents INFO[PTR] of each node, one by
one, of LIST. Now, however, we can stop once ITEM exceeds INFO[PTR]. (List sorted in
descending order)
Algorithm: SRCHSL(INFO, LINK,START, ITEM, LOC)
LIST is sorted list in memory. This algorithm finds the location LOC of the node
where ITEM first appear in LIST, or sets LOC=NULL.
1. Set PTR:=START.
2. Repeat Step 3 while PTR≠NULL:
3. If ITEM < INFO[PTR], then:
Set PTR:=LINK[PTR]. [PTR now points to the next node]
Else If ITEM=INFO[PTR],then
Set LOC:=PTR, and Exit. [Search is successful.]
Else:
LOC:=NULL , and Exit. [ITEM now exceeds INFO[PTR].]
[End of If structure.]
[End of Step 2 loop.]
4. Set LOC:=NULL.
5. Exit.
31
Search Linked List for insertion and deletion of Nodes:
Both insertion and deletion operations need searching the linked list.
• To add a new node, we must identify the logical predecessor (address of
previous node) where the new node is to be inserting.
• To delete a node, we must identify the location (addresses) of the node
to be deleted and its logical predecessor (previous node).
Basic Search Concept
Assume there is a sorted linked list and we wish that after each
insertion/deletion this list should always be sorted. Given a target value,
the search attempts to locate the requested node in the linked list.
Since nodes in a linked list have no names, we use two pointers, pre (for
previous)and cur (for current) nodes. At the beginning of the search, the
pre pointer is null and the cur pointer points to the first node (Head). The
search algorithm moves the two pointers together towards the end of the
list. Diagram in a next slide, shows the movement of these two pointers
through the list in an extreme case scenario: when the target value is
larger than any value in the list.
32
Moving of pre and cur pointers in searching a linked list
33
Values of pre and cur pointers in different cases
Linked List Operations
▪ add(9): Create a new node in memory to hold ‘9’
Node* newNode = new Node(9); 9
newNode
34
Linked List Operations
▪ add(9): Create a new node in memory to hold ‘9’
Node* newNode = new Node(9);
▪ Link the new node into the list
9
newNode
2 6 8 7 1
head
current
size=5 6
9
newNode
1
3
2
35
Building a Linked List
headNode size=0
List list;
36
Building a Linked List
headNode
2
headNode
currentNode
size=1
lastcurrentNode
size=0
List list;
list.add(2);
37
Building a Linked List
headNode
2
headNode
currentNode
size=1
lastcurrentNode
2 6
headNode
currentNode
size=2
lastcurrentNode
size=0
List list;
list.add(2);
list.add(6);
38
Building a Linked List
List.add(8); list.add(7); list.add(1);
2 6 7 1
headNode
currentNode
size=5
lastcurrentNode
8
39
Insertion at the beginning of a List
40
Insertion into a Linked List:
If a node N is to be inserted into the list between nodes A and B in a
linked list named LIST. Its schematic diagram would be:
41
Inserting at the Beginning of a List:
If the linked list is sorted list and new node has the least low value
already stored in the list i.e. (if New->info < Head->info) then new node
is inserted at the beginning / Top of the list.
Insertion at last
42
43
INSERTION AFTER A GIVEN NODE
Deletion from a Link List
2 6 7 1
headNode
currentNode
size=5
lastcurrentNode
8
44
Deletion from a Linked List
45
2 6 7 1
headNode
currentNode
size=5
lastcurrentNode
8
1
Deletion from a Linked List
2 7 1
headNode
currentNode
size=5
lastcurrentNode
8
1
2
46
Deletion from a Linked List
2 7 1
headNode
currentNode
size=4
lastcurrentNode
8
1
2
3
4
47
48
Deletion from the middle of the List
49
Deletion from the beginning of the List
50
Deletion at end of the List
Analysis of Linked List
▪ add
• we simply insert the new node after the current
node. So add is a one-step operation.
▪ remove
▪ remove is also a one-step operation
▪ find
▪ worst-case: may have to search the entire list
▪ back
▪ moving the current pointer back one node requires
traversing the list from the start until the node whose
next pointer points to current node.
51
Two-Way or Doubly-linked List
▪ Moving forward in a singly-linked list is easy;
moving backwards is not so easy.
▪ To move back one node, we have to start at the
head of the singly-linked list and move forward
until the node before the current.
▪ To avoid this we can use two pointers in a
node: one to point to next node and another to
point to the previous node:
element next
prev
52
Doubly-linked List
▪ Need to be more careful when adding or
removing a node.
▪ Consider add: the order in which pointers are
reorganized is important:
size=5
2 6 8 7 1
head
current
53
54
55
56
Deletion at last
57
Insertion at last, middle and start
Insertion in Doubly-linked List
size=5
2 6 8 7
head
current
1
9
newNode 1
58
Insertion in Doubly-linked List
size=5
2 6 8 7
head
current
1
9
newNode 1
2
59
Insertion in Doubly-linked List
size=5
2 6 8 7
head
current
1
9
newNode 1
2 3
60
Insertion in Doubly-linked List
size=5
2 6 8 7
head
current
1
9
newNode 1
2 4
3
61
Insertion in Doubly-linked List
size=6
2 6 8 7
head
current
1
9
newNode 1
2 4 3
62

More Related Content

PPTX
Data structure &amp; algorithms introduction
DOCX
Linked List
PPT
Introduction to data structure by anil dutt
PDF
Data structures
PDF
Data structures Basics
PDF
Data structure
PDF
Data Structures Notes 2021
PPT
Data structure lecture 1
Data structure &amp; algorithms introduction
Linked List
Introduction to data structure by anil dutt
Data structures
Data structures Basics
Data structure
Data Structures Notes 2021
Data structure lecture 1

What's hot (20)

PDF
Introduction to Data Structure
PPT
Unit 1 introduction to data structure
PDF
Introduction to data structure
PDF
Data structure ppt
PPTX
PDF
Data Structure and its Fundamentals
PPT
Data structures using c
PPT
Data Structure In C#
PPTX
What is Link list? explained with animations
PPT
Data structures & algorithms lecture 3
PPTX
Bca ii dfs u-1 introduction to data structure
PPT
Chapter 1( intro &amp; overview)
PPSX
Dynamic memory allocation
PDF
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
PDF
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
PPTX
Data structure & its types
PDF
2nd puc computer science chapter 3 data structures 1
PPTX
Linked list
PPTX
Data structure power point presentation
PPTX
DATA STRUCTURE
Introduction to Data Structure
Unit 1 introduction to data structure
Introduction to data structure
Data structure ppt
Data Structure and its Fundamentals
Data structures using c
Data Structure In C#
What is Link list? explained with animations
Data structures & algorithms lecture 3
Bca ii dfs u-1 introduction to data structure
Chapter 1( intro &amp; overview)
Dynamic memory allocation
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Data structure & its types
2nd puc computer science chapter 3 data structures 1
Linked list
Data structure power point presentation
DATA STRUCTURE
Ad

Similar to lect 2-DS ALGO(online).pdf (20)

PPT
lecture 02.2.ppt
PPTX
8.DATA STRUCTURES UNIT 1 AND 2 CS3301PPT.pptx
PPTX
DATA STRUCTURE AND ALGORITHM with linked list
PPTX
linked list in dsa python (presentation)
PPTX
unit 1_Linked list.pptx
PPTX
EC2311 – Data Structures and C Programming
PPTX
unit 1.pptx
PPTX
Engineering.CSE.DataStructure.Linkedlist.notes
PPTX
Lecture 5 data structures and algorithms
PDF
Data and File Structure Lecture Notes
PDF
Link list
PPTX
Data Structures and Algorithms: introduction
PDF
Bca data structures linked list mrs.sowmya jyothi
PPT
Sorting & Linked Lists
PDF
Data structure
PPT
Array linked list.ppt
PPTX
Data Structure
PDF
unit 2- linked list- PPT for btech students.pdf
PDF
unit 2- PPT.pdf
PPTX
Adt of lists
lecture 02.2.ppt
8.DATA STRUCTURES UNIT 1 AND 2 CS3301PPT.pptx
DATA STRUCTURE AND ALGORITHM with linked list
linked list in dsa python (presentation)
unit 1_Linked list.pptx
EC2311 – Data Structures and C Programming
unit 1.pptx
Engineering.CSE.DataStructure.Linkedlist.notes
Lecture 5 data structures and algorithms
Data and File Structure Lecture Notes
Link list
Data Structures and Algorithms: introduction
Bca data structures linked list mrs.sowmya jyothi
Sorting & Linked Lists
Data structure
Array linked list.ppt
Data Structure
unit 2- linked list- PPT for btech students.pdf
unit 2- PPT.pdf
Adt of lists
Ad

More from MuhammadUmerIhtisham (14)

PDF
LECT 10, 11-DSALGO(Hashing).pdf
PDF
LEC 12-DSALGO-GRAPHS(final12).pdf
PDF
Lect 13, 14 (final)AVL Tree and Rotations.pdf
PDF
LEC4-DS ALGO.pdf
PDF
LEC3-DS ALGO(updated).pdf
PDF
LEC 7-DS ALGO(expression and huffman).pdf
PDF
LEC 8-DS ALGO(heaps).pdf
PDF
LEC 5-DS ALGO(updated).pdf
PDF
LEC 6-DS ALGO(updated).pdf
PDF
lect 1-ds algo(final)_2.pdf
PDF
SMIU Discrete Structure Lecture 3 Section 3E.pdf
PDF
Discrete Structure Lecture #5 & 6.pdf
PDF
Discrete Structure Lecture #7 & 8.pdf
PDF
SMIU Lecture #1 & 2 Introduction to Discrete Structure and Truth Table.pdf
LECT 10, 11-DSALGO(Hashing).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
Lect 13, 14 (final)AVL Tree and Rotations.pdf
LEC4-DS ALGO.pdf
LEC3-DS ALGO(updated).pdf
LEC 7-DS ALGO(expression and huffman).pdf
LEC 8-DS ALGO(heaps).pdf
LEC 5-DS ALGO(updated).pdf
LEC 6-DS ALGO(updated).pdf
lect 1-ds algo(final)_2.pdf
SMIU Discrete Structure Lecture 3 Section 3E.pdf
Discrete Structure Lecture #5 & 6.pdf
Discrete Structure Lecture #7 & 8.pdf
SMIU Lecture #1 & 2 Introduction to Discrete Structure and Truth Table.pdf

Recently uploaded (20)

PDF
Complications of Minimal Access Surgery at WLH
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Institutional Correction lecture only . . .
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Cell Types and Its function , kingdom of life
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
master seminar digital applications in india
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
Complications of Minimal Access Surgery at WLH
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
O7-L3 Supply Chain Operations - ICLT Program
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Week 4 Term 3 Study Techniques revisited.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
Institutional Correction lecture only . . .
TR - Agricultural Crops Production NC III.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Supply Chain Operations Speaking Notes -ICLT Program
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Cell Types and Its function , kingdom of life
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
human mycosis Human fungal infections are called human mycosis..pptx
VCE English Exam - Section C Student Revision Booklet
Microbial disease of the cardiovascular and lymphatic systems
master seminar digital applications in india
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?

lect 2-DS ALGO(online).pdf

  • 1. Data Structures & Algorithm CSC-102 Lecture 2 Arrays & Link List Lecturer: Syeda Nazia Ashraf 1
  • 2. Arrays ▪ Array declaration: int x[6]; ▪ An array is collection of cells of the same type. ▪ The collection has the name ‘x’. ▪ The cells are numbered with consecutive integers. ▪ To access a cell, use the array name and an index: x[0], x[1], x[2], x[3], x[4], x[5] 2
  • 3. Array Layout (Linear-array) x[1] x[2] x[3] x[4] x[5] x[0] Array cells are contiguous in computer memory The memory can be thought of as an array 3
  • 4. Linear(1-Dimensional Array) A linear array A[8] consisting of numbers is pictured in following figure. 4 A linear array STUDENT consisting of the names of six students STUDENT[1] denotes John Brown, STUDENT[2] denotes Sandra Gold, and so on.
  • 5. 2-Dimensional Array 5 A chain of 28 stores, each store having 4 departments, may lists its weekly sales first subscript denotes the store and the second subscript the department. SALES is the name given to the Array. SALES[1,1]=2872, SALES[1,2]=805, SALES[1,3]=3211,……..,SALES[28,4]=282 The size of this array is denoted by 28 X 4 (read 28 by 4), since it contains 28 rows (the horizontal lines of numbers) and 4 columns (the vertical lines of numbers). Such arrays are called Matrices in mathematics, and tables in business applications.
  • 8. 8
  • 9. Data Structure Operations 9 The following four operations play a major role: 1. Traversing: Accessing each record exactly once so that certain items in the record may be processed. (this accessing and processing is sometimes called “visiting” the record.) 2. Searching: Finding the location of the record with a given key value, or finding the locations of all records which satisfy one or more conditions. 3. Inserting: Adding a new record to the structure. 4. Deleting: Removing a record from the structure. Sometimes two or more of the operations may be used in a given situation; e.g., we may want to delete the record with a given key, which may mean we first need to search for the location of the record. The following operations, which are used in special situations, will also be considered: 1. Sorting: Arranging the records in some logical order (e.g., alphabetically according to some NAME key, or in numerical order according to some NUMBER key, such as social security number or account number or student id) 2. Merging: Combining the records in two different sorted files into a single sorted file.
  • 10. ADT • An ADT, is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented. • This means that we are concerned only with what the data is representing and not with how it will eventually be constructed. • By providing this level of abstraction, we are creating an encapsulation around the data. The idea is that by encapsulating the details of the implementation, we are hiding them from the user’s view. This is called information hiding. • The implementation of an abstract data type, often referred to as a data structure, will require that we provide a physical view of the data using some collection of programming constructs and primitive data types. 10
  • 11. 11 Figure shows a picture of what an abstract data type is and how it operates. The user interacts with the interface, using the operations that have been specified by the abstract data type. The abstract data type is the shell that the user interacts with. The implementation is hidden one level deeper. The user is not concerned with the details of the implementation. ADT
  • 13. 13
  • 14. 14
  • 15. Data Abstraction and Abstract Data Types (ADT) • A data type is a template for objects and a set of operations that define the behavior of the objects ( or Instances) of that type. • An abstract Data Type (ADT) is a data type in which the implementation details are hidden and the user is concerned with the properties ( or behavior) of that type. • An ADT has two components: - Interface (the behavior) - Implementation • Example: - int, float 15
  • 16. Implementation Abstract Data Type • The data structures used to implement the data type can only be accessed through the interface. • Any change in the implementation does not change the user programs as long as the interface remains the same • This is also known as the data encapsulation or data abstraction. Interface 1 Interface 2 Interface 3 Interface 4 Implementation 16
  • 17. 17
  • 18. Linked List • A list is an abstract data type that implements an ordered collection of values, where the same value may occur more than once. • Create a structure called a Node. • The object field will hold the actual list element. • The next field in the structure will hold the starting location of the next node. • Chain the nodes together to form a linked list. 18 object next
  • 19. Linked List ▪ Picture of our list (2, 6, 8, 7, 1) stored as a linked list: 2 6 8 7 1 head current size=5 19
  • 21. Linked List Note some features of the list: ▪ Need a head to point to the first node of the list. Otherwise we won’t know where the start of the list is. ▪ The current here is a pointer, not an index. ▪ The next field in the last node points to nothing. We will place the memory address NULL which is guaranteed to be inaccessible. 21
  • 22. Linked List Actual picture in memory 1051 1052 1055 1059 1060 1061 1062 1063 1064 1056 1057 1058 1053 1054 2 6 8 7 1 1051 1063 1057 1060 0 head 1054 1063 current 1065 Tail / null
  • 23. Real world examples: Linked lists • Road train • File blocks on disk
  • 24. Real world examples: Linked lists 24 In real life, objects often appear in simple lists. For example,Companies may maintain a list of Employees, Banks may keep a list of Bank Accounts, a Person may keep a list of "Things to Do".etc.. A List ADT allows us to access any of its elements at any time as well as insert or remove elements anywhere in the list at any time. The list will automatically shift the elements around in memory to make the needed room or reduce the unused space. The general list is the most flexible kind of list in terms of its capabilities. We use a general List whenever we have elements coming in and being removed in a random order. For example, when we have a shelf of library books, we may need to remove a book from anywhere on the shelf and we may insert books back into their proper location when they are returned.
  • 25. Operations on Linked List: There are several operations associated with linked list i.e. a) Traversing a Linked List Suppose we want to traverse LIST in order to process each node exactly once. The traversing algorithm uses a pointer variable PTR which points to the node that is currently being processed. Accordingly, PTR->NEXT points to the next node to be processed so, 25
  • 26. 26 PTR:=START [ Moves the pointer to the first node of the list] PTR:=LINK[PTR] [ Moves the pointer to the next node in the list.] INFO[PTR] [Process information at the node]
  • 27. 27
  • 28. 28 Algorithm: (Traversing a Linked List) Let LIST be a linked list in memory. This algorithm traverses LIST, applying an operation PROCESS to each element of list. The variable PTR point to the node currently being processed. 1. Set PTR:=START. [Initializes pointer PTR.] 2. Repeat Steps 3 and 4 while PTR ≠ NULL. 3. Apply PROCESS to INFO[PTR]. 4. Set PTR:= LINK[PTR]. [PTR now points to the next node] [End of Step 2 loop.] 5. Exit.
  • 29. 29 b) Searching a Linked List:(UNSORTED LIST) Suppose the data in LIST are not necessarily sorted. Then one searches for ITEM in LIST by traversing through the list using a pointer variable PTR and comparing ITEM with the contents INFO[PTR] of each node, one by one, of LIST. Before we update the pointer PTR by PTR:=LINKPTR], we require two tests. First we have to check to see whether we have reached the end of the LIST i.e. PTR=NULL. If not, then we check to see whether INFO[PTR]=ITEM. The two tests cannot be performed at the same time, since INFO[PTR] is not defined when PTR=NULL. Accordingly we use the First test to control the execution of a loop, and we let the second test take place inside the loop. Algorithm: SEARCH(INFO, LINK,START, ITEM, LOC) LIST is a linked list in the memory. This algorithm finds the location LOC of the node where ITEM first appear in LIST, or sets LOC=NULL. 1. Set PTR:=START. 2. Repeat Step 3 while PTR≠NULL: 3. If ITEM = INFO[PTR], then: Set LOC:=PTR, and Exit. [Search is successful.] Else: Set PTR:=LINK[PTR]. [PTR now points to the next node] [End of If structure.] [End of Step 2 loop.] 4. Set LOC:=NULL. [Search is unsuccessful.] 5. Exit.
  • 30. 30 b) Searching a Linked List:(SORTED LIST) Suppose the data in LIST are sorted. Again we search for ITEM in LIST by traversing the list using a pointer variable PTR and comparing ITEM with the contents INFO[PTR] of each node, one by one, of LIST. Now, however, we can stop once ITEM exceeds INFO[PTR]. (List sorted in descending order) Algorithm: SRCHSL(INFO, LINK,START, ITEM, LOC) LIST is sorted list in memory. This algorithm finds the location LOC of the node where ITEM first appear in LIST, or sets LOC=NULL. 1. Set PTR:=START. 2. Repeat Step 3 while PTR≠NULL: 3. If ITEM < INFO[PTR], then: Set PTR:=LINK[PTR]. [PTR now points to the next node] Else If ITEM=INFO[PTR],then Set LOC:=PTR, and Exit. [Search is successful.] Else: LOC:=NULL , and Exit. [ITEM now exceeds INFO[PTR].] [End of If structure.] [End of Step 2 loop.] 4. Set LOC:=NULL. 5. Exit.
  • 31. 31 Search Linked List for insertion and deletion of Nodes: Both insertion and deletion operations need searching the linked list. • To add a new node, we must identify the logical predecessor (address of previous node) where the new node is to be inserting. • To delete a node, we must identify the location (addresses) of the node to be deleted and its logical predecessor (previous node). Basic Search Concept Assume there is a sorted linked list and we wish that after each insertion/deletion this list should always be sorted. Given a target value, the search attempts to locate the requested node in the linked list. Since nodes in a linked list have no names, we use two pointers, pre (for previous)and cur (for current) nodes. At the beginning of the search, the pre pointer is null and the cur pointer points to the first node (Head). The search algorithm moves the two pointers together towards the end of the list. Diagram in a next slide, shows the movement of these two pointers through the list in an extreme case scenario: when the target value is larger than any value in the list.
  • 32. 32 Moving of pre and cur pointers in searching a linked list
  • 33. 33 Values of pre and cur pointers in different cases
  • 34. Linked List Operations ▪ add(9): Create a new node in memory to hold ‘9’ Node* newNode = new Node(9); 9 newNode 34
  • 35. Linked List Operations ▪ add(9): Create a new node in memory to hold ‘9’ Node* newNode = new Node(9); ▪ Link the new node into the list 9 newNode 2 6 8 7 1 head current size=5 6 9 newNode 1 3 2 35
  • 36. Building a Linked List headNode size=0 List list; 36
  • 37. Building a Linked List headNode 2 headNode currentNode size=1 lastcurrentNode size=0 List list; list.add(2); 37
  • 38. Building a Linked List headNode 2 headNode currentNode size=1 lastcurrentNode 2 6 headNode currentNode size=2 lastcurrentNode size=0 List list; list.add(2); list.add(6); 38
  • 39. Building a Linked List List.add(8); list.add(7); list.add(1); 2 6 7 1 headNode currentNode size=5 lastcurrentNode 8 39
  • 40. Insertion at the beginning of a List 40 Insertion into a Linked List: If a node N is to be inserted into the list between nodes A and B in a linked list named LIST. Its schematic diagram would be:
  • 41. 41 Inserting at the Beginning of a List: If the linked list is sorted list and new node has the least low value already stored in the list i.e. (if New->info < Head->info) then new node is inserted at the beginning / Top of the list.
  • 43. 43 INSERTION AFTER A GIVEN NODE
  • 44. Deletion from a Link List 2 6 7 1 headNode currentNode size=5 lastcurrentNode 8 44
  • 45. Deletion from a Linked List 45 2 6 7 1 headNode currentNode size=5 lastcurrentNode 8 1
  • 46. Deletion from a Linked List 2 7 1 headNode currentNode size=5 lastcurrentNode 8 1 2 46
  • 47. Deletion from a Linked List 2 7 1 headNode currentNode size=4 lastcurrentNode 8 1 2 3 4 47
  • 48. 48 Deletion from the middle of the List
  • 49. 49 Deletion from the beginning of the List
  • 50. 50 Deletion at end of the List
  • 51. Analysis of Linked List ▪ add • we simply insert the new node after the current node. So add is a one-step operation. ▪ remove ▪ remove is also a one-step operation ▪ find ▪ worst-case: may have to search the entire list ▪ back ▪ moving the current pointer back one node requires traversing the list from the start until the node whose next pointer points to current node. 51
  • 52. Two-Way or Doubly-linked List ▪ Moving forward in a singly-linked list is easy; moving backwards is not so easy. ▪ To move back one node, we have to start at the head of the singly-linked list and move forward until the node before the current. ▪ To avoid this we can use two pointers in a node: one to point to next node and another to point to the previous node: element next prev 52
  • 53. Doubly-linked List ▪ Need to be more careful when adding or removing a node. ▪ Consider add: the order in which pointers are reorganized is important: size=5 2 6 8 7 1 head current 53
  • 54. 54
  • 55. 55
  • 57. 57 Insertion at last, middle and start
  • 58. Insertion in Doubly-linked List size=5 2 6 8 7 head current 1 9 newNode 1 58
  • 59. Insertion in Doubly-linked List size=5 2 6 8 7 head current 1 9 newNode 1 2 59
  • 60. Insertion in Doubly-linked List size=5 2 6 8 7 head current 1 9 newNode 1 2 3 60
  • 61. Insertion in Doubly-linked List size=5 2 6 8 7 head current 1 9 newNode 1 2 4 3 61
  • 62. Insertion in Doubly-linked List size=6 2 6 8 7 head current 1 9 newNode 1 2 4 3 62