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

What's hot

Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
Prof Ansari
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
kalyanineve
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
Zaid Shabbir
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
Prof. Dr. K. Adisesha
 
Data structures
Data structuresData structures
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
Hitesh Mohapatra
 
Data structures using c
Data structures using cData structures using c
Data structures using c
Prof. Dr. K. Adisesha
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animations
PratikNaik41
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3
Poojith Chowdhary
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
Rai University
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
MUHAMMAD AAMIR
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Moniruzzaman _
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Balwant Gorad
 
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARIntroduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
BHARATH KUMAR
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
Rameesha Sadaqat
 
2nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 12nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 1
Aahwini Esware gowda
 
Linked list
Linked listLinked list
Linked list
Md. Afif Al Mamun
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation
Anil Kumar Prajapati
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
Rohit Rai
 

What's hot (20)

Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Data structures
Data structuresData structures
Data structures
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animations
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARIntroduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
 
2nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 12nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 1
 
Linked list
Linked listLinked list
Linked list
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 

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

DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
sarala9
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
SaralaT3
 
Stack and queue power point presentation data structure and algorithms Stack-...
Stack and queue power point presentation data structure and algorithms Stack-...Stack and queue power point presentation data structure and algorithms Stack-...
Stack and queue power point presentation data structure and algorithms Stack-...
abhaysingh19149
 
Chapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.pptChapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.ppt
NORSHADILAAHMADBADEL
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
selemonGamo
 
unit 2- PPT.pdf
unit 2- PPT.pdfunit 2- PPT.pdf
unit 2- PPT.pdf
PranavMakwana6
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyMalikireddy Bramhananda Reddy
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
SrinivasanCSE
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
Rajitha Reddy Alugati
 
Data structure
 Data structure Data structure
Data structure
Shahariar limon
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
DEEPAK948083
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGEST
Swapnil Mishra
 
3.ppt
3.ppt3.ppt
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
Adams Sidibe
 
DSA - Copy.pptx
DSA - Copy.pptxDSA - Copy.pptx
DSA - Copy.pptx
BishalChowdhury10
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
blessyboban92
 
Data Structure
Data Structure Data Structure
Data Structure
Ibrahim MH
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introduction
Mandeep Singh
 

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

DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 
Stack and queue power point presentation data structure and algorithms Stack-...
Stack and queue power point presentation data structure and algorithms Stack-...Stack and queue power point presentation data structure and algorithms Stack-...
Stack and queue power point presentation data structure and algorithms Stack-...
 
Chapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.pptChapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.ppt
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
unit 2- PPT.pdf
unit 2- PPT.pdfunit 2- PPT.pdf
unit 2- PPT.pdf
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
 
Data structure
 Data structure Data structure
Data structure
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGEST
 
Intro ds
Intro dsIntro ds
Intro ds
 
3.ppt
3.ppt3.ppt
3.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
 
DSA - Copy.pptx
DSA - Copy.pptxDSA - Copy.pptx
DSA - Copy.pptx
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
Data Structure
Data Structure Data Structure
Data Structure
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introduction
 

More from MuhammadUmerIhtisham

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

More from MuhammadUmerIhtisham (14)

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

Recently uploaded

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 

Recently uploaded (20)

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 

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