SlideShare a Scribd company logo
1 of 61
CS261
DATA STRUCTURES & ALGORITHMS
(WEEK-2)
LECTURE-3 & 4
INTRODUCTION TO DATA STRUCTURES &
ALGORITHMS
Lecturer
Azka Aziz
Azka.a@scocs.edu.pk
Data structures &
Algorithms
LECTURE#02 ARRAYS
Course contents
Array Data Structure (Declaration, Initialization, Updation)
Why we need Arrays?
Pros & Cons
Character String as Array
Pointers: Increment & Decrement
Multi-Dimensional Array
Exercises using Arrays
Home work using Arrays
Array
An array is a homogeneous data structure that can contain multiple elements.
In most programming languages array elements are stored in contiguous
memory space. This data structure is homogeneous since all elements stored
are of same type.
0 1 2 3 4 5 6 7 8 9
array
Starting index Last index
Remember: number of
elements are 10
Array
Array name is reference to memory location where first elment of array is stored
Array elmements can be accessed using array name and a non-negative integer index e.g.
say records is an array then records[2] refers to 3rd elment of array
Index values for an N element array range from 0 to N-1
Array elements can be accessed randomly (no sequence is required to follow for it)
0 1 2 3 4 5 6 7 8 9
Array Declaration
Syntax : datatype anArrayname[sizeofArray];
int data[10];
As the result of above statement execution an integer array of ten elements is
created within the memory of computer
First valid index is 0 and last valid index is 9
Array elements can be refered as data[0], data[1], data[2], … , data[9]
0 1 2 3 4 5 6 7 8 9
Array initialization
Syntax : datatype anArrayname[sizeofArray]= {comma separated
values};
int data[10]={5, 3, 12, 23, 8, 37, 6, 10, 55, 4};
As the result of above statement execution an integer array of ten elements is
created within the memory of computer and are initialized with provided values
0 index value is initialized with 5, 1 index value is initialized with 3, 2 index value
is initialized with 12 so on and so forth
5 3 12 23 8 37 6 10 55 4
0 1 2 3 4 5 6 7 8 9
Elements
Indexes
Array initialization
int data[5];
data[0]=6; data[1]=12; data[2]=18; data[3]=24; data[4]=30;
As the result of first statement execution an integer array of ten elements is created
within the memory of computer. Statements in second line are initializing array
elements:
6
12
18
24
30
0
1
2
3
4
index
Array values
Array … first program
#include <iostream>
int main(int argc, char** argv) {
int values[10]={5, 10, 3, 18, 7, 12, 34, 26, 0, 47};
for(int i=0; i<10; i++)
std::cout<<values[i]<<std::endl;
return 0;
}
A simple program that initializes a ten element integer
array and prints all elements using for loop
Array … Updating elements
array[index] = new-value;
A declared array element can be assigned a valid value during within the scope of
array. See below:
#include <iostream>
int main(int argc, char** argv) {
int values[10]={1,2,3,4,5,6,7,8,9,10};
values[2]=20; values[4]=30; values[9]=11;
return 0;
}
Array … search an element
Write down a small program
using an array containing ten
integer values (properly
initialized). Input an integer
value from user and search
whether given value exists in
array or not.
Program:
Array … Why we need it?
It is often required during programming that some operation is required to be
applied over set of fixed size data items e.g. search a specific item from a set of
values, sum the values of list of numbers, initialize all quantities within a list with
some given value etc
To meet the situations above and many more, almost all programming languages
support arrays or similar data structures
Wherever we want to use multiple variables of same type of data, array can be very
handy
Array allows to declare and initialize multiple variables of same type using single
statement
Instead of apply some operation on individual items of same type, we can use a
loop to do the same on an array (very convenient)
Array … pros and cons
Advantages Disadvantages
It is used to represent multiple data items of same
type by using only single name
Insertion / deletion of elements is not straight
forward and requires a lot of effort
It can be used to implement other data structures
like linked lists, stacks, queues, trees, graphs etc.
Most programming languages offer static arrays
not allowing elements beyond defined boundaries
Common mathematical models e.g. matrices,
tables can be represented by 2D arrays
Larger arrays may cause loss of memory i.e. whole
memory is allocated even when few elements are
availablel
Elements can be accessed randomly Multi-dimension arrays are neither easier to
implement nor to maintain
Suitable data structure when elements are already
known
Few languages (C / C++) does not provide array
boundary check introducing inappropriate access
to application data
One can use same name for a collection of similar
elements
We must know in advance that how many
elements are to be stored in array
character string as array
In C/C++ strings are treated like as an array of characters e.g.
char message[]=“welcome”;
Above character is stored in memory like:
w e l c o m e 0
Every string is terminated by a null character ‘0’
character string as array …
If we initialize a character array with a size e.g.
char message[12] = “welcome”;
Then memory actually looks like:
Last four characters spaces are unused.
w e l c o m e 0
character string as array …
We can actually access individual elements of a character array:
char message[]=“welcome”;
std:cout<<message[3]<<std:endl;
Output:
c
character string as array …
Creating a string as character array requires at compile time how many character
will be stored in it. Such arrays are called static arrays. Examples below:
char message[]=“message”; // eight characters will be allocated for this array
char country[20]=“Pakistan”; // nine chracters will be allocated for this array
Array name AND pointer
Array name is a pointer and it points to initial position of memory allocated to store
array contents. It can be assigned to a character pointer type of variable and that in
return can access array contents like original array name. Example below:
char message[]="welcome";
char *pointer=message;
std::cout<<pointer[3]<<std::endl;
Multi-dimensional arrays
C/C++ allows multi-dimensional arrays. Following is the syntax for declaring them:
datatype array_name[dim1][dim2]….[dimN];
A typical two dimensional integer array can be declared as:
int arr[5][4];
This 2D array can be imagined as a table and can be visualized as:
arr[0][0] arr[0][1] arr[0][2] arr[0][3]
arr[1][0] arr[1][1] arr[1][2] arr[1][3]
arr[2][0] arr[2][1] arr[2][2] arr[2][3]
arr[3][0] arr[3][1] arr[3][2] arr[3][3]
arr[4][0] arr[4][1] arr[4][2] arr[4][3]
Row 0
Row 1
Row 2
Row 3
Row 4
Col 0 Col 3
Col 2
Col 1
Multi-dimensional arrays
A multi-dimensional array can be initialized by specifying each row values separated
by commas as below:
int arr[2][3]={{1,2,3}, {1,2,3}};
1 2 3
1 2 3
Exercise questions
Q#01. Write down a function with following prototype:
int find(data, target)
where data is an integer array and target is an integer value. Find() searches through data
and returns the index of value that is equal to target. It returns -1 if no elment in data is
equal to target.
Q#02. Write down a function with following prototype:
int find(data, target)
where data is an integer array and target is an integer value. Find() searches through data
and returns the index of last occurance of value that is equal to target. It returns -1 if no
elment in data is equal to target.
Exercise questions
Q#03. Write down a function with following prototype:
int count(data, target)
where data is an integer array and target is an integer value. Count() searches through data
and number of occurances of target value within the data. It returns 0 if no elment in data is
equal to target.
Q#04. Write down a function with following prototype:
void double(data)
where data is an integer array. Double() updates all values within the data with double of its
original values.
Homework for next class
Q#01. Write a function equal(data1, data2) as below:
int equal(data1, data2) where both data1 and data2 are integer arrays. Equal()
returns 1 if both arrays have same values and same order. It returns 0 otherwise.
Example:
If data1={1,2,3} and data2={1,2,3}, equal() returns 1
If data1={1,2,3} and data2={2, 1,3}, equal() returns 0
If data1={1,2,3} and data2={4,2,3}, equal() returns 0
If data1={1,2,3} and data2={1,2,3,4}, equal() returns 0
If data1={1,2,3} and data2={4,5,6}, equal() returns 0
Homework for next class
Q#01. Write a function equal(data1, data2) as below:
int equal(data1, data2) where both data1 and data2 are integer arrays. Equal()
returns 1 if both arrays have same values. It returns 0 otherwise.
Example:
If data1={1,2,3} and data2={1,2,3}, equal() returns 1
If data1={1,2,3} and data2={2, 1,3}, equal() returns 1
If data1={1,2,3} and data2={4,2,3}, equal() returns 0
If data1={1,2,3} and data2={1,2,3,4}, equal() returns 0
If data1={1,2,3} and data2={4,5,6}, equal() returns 0
Assignment 01
Assignment 01 is ready:
Data structures &
Algorithms
LECTURE#04-A LINKED LISTS
Course contents
Linked List
Linked List ADT
Linked List Representation
Linked List Operations (Idea & Implementation)
PrintAll
AddNode
AppendNode
InsertNode
DeleteNode
Size
Linked Lists
A finite and ordered sequence of items
connected together through links is
called a linked list or simply a list.
Items in a linked list are generally called nodes
A node in a linked list consists of two parts i. Data
part ii. Link part
Data part is for storage of value(s) and link part
contains the address of simply another node of
same list
First node is commonly known as start node
Linked Lists …
A list object contains the reference to start node only
First node is directly accessed by linked-list object and other nodes are
accessed one by one using the links to other elements
Since list nodes can only be accessed one by one sequentially, list data
structure is also categorized as a linear data structure
Linked List
Linked Lists …
List elements are ordered only in a sense that they can be accessed one by
one beginning from start node (ordered does not mean sorted)
A list is said to be empty if its start node points to NULL
NULL is a special pointer that indicates the end of list
First node of list (start node) is called the head and last node is called the tail
List can grow and shrink dynamically (generally no limit on number of
elements)
When list grows, memory allocated for it also grows i.e. memory allocated for
list directly refers to number of nodes in the list
ADT
An abstract data type (ADT) is a mathematical model for data types
where a data type is defined by its behavior (semantics) from the point
of view of a user of the data, specifically in terms of possible values,
possible operations on data of this type, and the behavior of these
operations.
https://en.wikipedia.org/wiki/Abstract_data_type
Linked list ADT
Note: More operations can be defined as per needs.
Linked list ADT … Node operations
Operation Description
Node(int) Construtor that initializes node ‘data’ members with
given value & node pointer ‘next’ to NULL
void Set_data(int) Sets the data member ‘data’ with provided value
int get_data() Returns current value of ‘data’
void set_next(Node*) Sets the data member ‘next’ with provided ‘pointer’
Node* get_next() Returns the current value of ‘next’ pointer
Linked list ADT … linklist operations
Operation Description Pseudo Code
LinkList() A constructor that
initializes data member
‘start’ to NULL
 Assign NULL to ‘start’
size() A method that returns
the size of Linked List
i.e. number of elements
in it
 Take a temprorary node pointer ‘temp’
and point it to ‘start’ node pointer
 Set ‘count’ to zero
 It traverses all nodes one by one by
pointing ‘temp’ pointer to ‘next’ pointer
and increasing the ‘count’ by one in
every iteration
 Iterations stop when ‘temp’ points to
NULL address
 At this point value of ‘count’ is returned
Linked list ADT … linklist operations
Operation Description Pseudo Code
print_all() Prints the ‘data’ values
for all nodes in Linked
List
 Take a temprorary node pointer ‘temp’
and point it to ‘start’ node pointer
 It traverses all nodes one by one by
printing value of ‘data’ for node ‘temp’ is
pointing to and then pointing ‘temp’ to
‘next’ pointer
 Iterations stop when ‘temp’ points to
NULL value
Linked list operations … print all
Linked list operations … add node
Operation Description Pseudo Code
add_node(key) Adds a new node
to start of list
 Creates a new node ‘temp’ with provided
‘key’ as ‘data’ value
 Points ‘next’ pointer to ‘start’
 Moves ‘start’ to ‘temp’
Linked list operations … append node
Operation Description Pseudo Code
append_node(key) Adds a new
node to end of
list
 Create a new node ‘n’ using given ‘key’ as
its ‘data’ and NULL as ‘next’ pointer
 Creates a node pointer ‘temp’ and point it
to start
 If ‘temp’ points to NULL, assign ‘n’ to ‘start’
 Otherwise, traverse ‘temp’ to the last
nodes of list using ‘next’ pointers of
intermediate nodes
 Assign ‘n’ to ‘next’ of ‘temp’
Linked List operations … append node
Linked List operations … search node
Operation Description Pseudo Code
Search_node(key) Searches node
from list whose
‘data’ value is
equal to ‘key’
provided and
returns its
reference
 Take a node pointer ‘temp’ and point it to
‘start’
 Iterate ‘temp’ through list nodes until
either a node with ‘data’ equal to ‘key’ is
found or list ends (‘temp’ points to NULL)
 Return the node pointer ‘temp’ is pointing
to
Linked List operations … search node
No node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure
‘NULL’ value is return as response
Linked List operations … search node
Node in Linked List having ‘data 4’ as its value same as of ‘key’
Pointer to ‘data 4’ is returned as response
Linked List operations … insert node
Operation Description Pseudo Code
insert_node(after,
key)
Inserts a new
node into
Linked List
after a node
with given
value
 Call the search(after) procedure as
described earlier
 If Node pointer returned as above call is
equl to NULL, insertion not possible
 Otherwise (a valid node pointer is
returned say ‘temp’), create a new node ‘n’
 Set ‘key’ to the ‘data’ of ‘n’ and set ‘next’ of
‘temp’ to ‘next’ of ‘n’
Linked List operations … insert node
A new node needs to be deleted after ‘data2’
Linked List operations … append node
Operation Description Pseudo Code
Append_node(key) Adds a new
node to end of
list
 Create a new node ‘n’ using given ‘key’ as
its ‘data’ and NULL as ‘next’ pointer
 Creates a node pointer ‘temp’ and point it
to start
 If ‘temp’ points to NULL, assign ‘n’ to ‘start’
 Otherwise, traverse ‘temp’ to last nodes
using ‘next’ pointers of intermediate nodes
 Assign ‘n’ to ‘next’ of ‘temp’
Linked List operations … delete node
Operation Description Pseudo Code
delete_node(key) Deletes node from
list whose ‘data’
value is equal to
‘key’ provided. List
remains in tact
after delete
operation has
executed
 Take a node pointer ‘temp’ and point it
to ‘start’
 Iterate ‘temp’ through list nodes until
either a node with matching ‘data’ is
found or list ends
 If list has ended, nothing happens
 If node with ‘data’ equal to ‘key’ was
found at ‘start’, ‘start’ pointer starts
pointing to its ‘next’ node
 If node with ‘data’ equal to ‘key’ was
found after ‘start’, list pointers are
adjusted and that node is removed from
list
Linked List operations … delete node
No node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure
Linked List remains same, nothing happens
Linked List operations … delete node
‘start’ node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure
‘start’ pointer points to next node in list, matching node is removed from list
Linked List operations … delete node
A node in Linked List after ‘start’ had same value of ‘data’ as of ‘key’ provided to procedur
Linked List remains intact with ‘data 3’ node removed
Linked List Operations … C++ Code
Create two classes i. Node ii. LinkList as their ADT
Node class is simple it just contains two data members i. data (int data type for simplicity) ii.
next (Node pointer) for pointing to next node in list
Create public constructor for Node class
Create setters and getters for Node data members
Node class code is all set
Linked List Operations … node class
class Node {
int data;
Node* next;
public:
Node(){data=0;next=0;};
void set_data(int d){this->data=d;};
int get_data(){ return this->data; };
void set_next(Node *n){this->next=n;};
Node* get_next(){return this->next;};
};
Linked List Operations … C++ Code
Create class LinkList with a single data member i. start (a node pointer) pointing to head node of
Linked List
Define constructor and operations as discussed earlier
Selected operations code is given as:
Note: implement yourself remaining function belonging to LinkList class
Linked List Operations … linklist class
class LinkList{
Node* start;
public:
LinkList();
void add_node(int);
void append_node(int);
int size();
Node* search(int);
void delete_node(int);
void insert(int, int);
void print_all();
};
Linked List Operations … linklist class
LinkList :: LinkList()
{
this->start = 0;
}
void LinkList::add_node(int key)
{
Node* n=new Node();
n->set_data(key);
n->set_next(this->start);
this->start = n;
}
Linked List Operations … linklist class
int LinkList::size()
{
int count = 0;
Node *temp = this->start;
while(temp)
{
count++;
temp = temp->get_next();
}
return count;
}
Linked List Operations … linklist class
Node* LinkList::search(int key)
{
Node *temp = this->start;
while(temp && temp->get_data()!= key)
{
temp = temp->get_next();
}
return temp;
}
Linked List Operations … main method
int main(int argc, char** argv) {
LinkList list;
list.add_node(2);
list.append_node(10);
list.add_node(7);
list.insert(3,25);
list.print_all();
list.delete_node(30);
list.print_all();
return 0;
}
Structure of Link List
Struct{
Int data;
Struct node * link ;
};
Struct node * ptfirst = null; (null = 0)
Main Algorithm
Start
Repeat (loop) while true (true = 1)
[menu option]
Write(cout) (“1: Insert ”);
Write (“2: display ”);
Write (“3: Insert first ”);
Write (“4: Insert after ”);
Write (“5: Insert before ”);
Write (“6: Delete ”);
Write (“7: Exite ”);
Write (“Enter option number ”);
Read (cin) option number (option_number)
Select option_number
It include switch case
Option 1
Write (“ Insert value ”);
Read value
Insert (value)
Option 2
Insert (value)
[check for empty list]
If ptfirst == NULL ; then
Temp = new node ;
Temp -> link = ptfirst;
Ptfirst = temp;
Else
Ptfirst = temp ;
Repeat while loop (temp != NULL)
Temp = temp -> link;
[End of loop of step 2a]
Temp-> link = new node ;
Temp = temp -> link ;
[End of if-else structure ]
Temp -> data = value;
Temp -> link = NULL;
Display();
if ptfirst == NULL then
write(“list is empty”);
return
[End of if structure ]
temp = ptfist;
repeat while (temp != NULL)
◦ write (temp -> data)
◦ Temp -> temp -> link ;
[End of loop]
return ;
Algorithm for inset first
Insert first(value)
[creat a new node ]
Temp = new node;
Temp -> data = value;
Temp -> link = ptfirst;
Ptfirst = temp;
Return;

More Related Content

Similar to Data structure.pptx

Similar to Data structure.pptx (20)

Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Array assignment
Array assignmentArray assignment
Array assignment
 
About Array
About ArrayAbout Array
About Array
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
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
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays
ArraysArrays
Arrays
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 

More from SajalFayyaz

Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.pptSajalFayyaz
 
data structure 9.pptx
data structure 9.pptxdata structure 9.pptx
data structure 9.pptxSajalFayyaz
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptxSajalFayyaz
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
Data structure 6.pptx
Data structure 6.pptxData structure 6.pptx
Data structure 6.pptxSajalFayyaz
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
data structure3.pptx
data structure3.pptxdata structure3.pptx
data structure3.pptxSajalFayyaz
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 

More from SajalFayyaz (10)

Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
data structure 9.pptx
data structure 9.pptxdata structure 9.pptx
data structure 9.pptx
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptx
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Data structure 6.pptx
Data structure 6.pptxData structure 6.pptx
Data structure 6.pptx
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
data structure3.pptx
data structure3.pptxdata structure3.pptx
data structure3.pptx
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 

Recently uploaded

Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Delhi Call girls
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改atducpo
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...shivangimorya083
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 

Recently uploaded (20)

Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 

Data structure.pptx

  • 1. CS261 DATA STRUCTURES & ALGORITHMS (WEEK-2) LECTURE-3 & 4 INTRODUCTION TO DATA STRUCTURES & ALGORITHMS Lecturer Azka Aziz Azka.a@scocs.edu.pk
  • 3. Course contents Array Data Structure (Declaration, Initialization, Updation) Why we need Arrays? Pros & Cons Character String as Array Pointers: Increment & Decrement Multi-Dimensional Array Exercises using Arrays Home work using Arrays
  • 4. Array An array is a homogeneous data structure that can contain multiple elements. In most programming languages array elements are stored in contiguous memory space. This data structure is homogeneous since all elements stored are of same type. 0 1 2 3 4 5 6 7 8 9 array Starting index Last index Remember: number of elements are 10
  • 5. Array Array name is reference to memory location where first elment of array is stored Array elmements can be accessed using array name and a non-negative integer index e.g. say records is an array then records[2] refers to 3rd elment of array Index values for an N element array range from 0 to N-1 Array elements can be accessed randomly (no sequence is required to follow for it) 0 1 2 3 4 5 6 7 8 9
  • 6. Array Declaration Syntax : datatype anArrayname[sizeofArray]; int data[10]; As the result of above statement execution an integer array of ten elements is created within the memory of computer First valid index is 0 and last valid index is 9 Array elements can be refered as data[0], data[1], data[2], … , data[9] 0 1 2 3 4 5 6 7 8 9
  • 7. Array initialization Syntax : datatype anArrayname[sizeofArray]= {comma separated values}; int data[10]={5, 3, 12, 23, 8, 37, 6, 10, 55, 4}; As the result of above statement execution an integer array of ten elements is created within the memory of computer and are initialized with provided values 0 index value is initialized with 5, 1 index value is initialized with 3, 2 index value is initialized with 12 so on and so forth 5 3 12 23 8 37 6 10 55 4 0 1 2 3 4 5 6 7 8 9 Elements Indexes
  • 8. Array initialization int data[5]; data[0]=6; data[1]=12; data[2]=18; data[3]=24; data[4]=30; As the result of first statement execution an integer array of ten elements is created within the memory of computer. Statements in second line are initializing array elements: 6 12 18 24 30 0 1 2 3 4 index Array values
  • 9. Array … first program #include <iostream> int main(int argc, char** argv) { int values[10]={5, 10, 3, 18, 7, 12, 34, 26, 0, 47}; for(int i=0; i<10; i++) std::cout<<values[i]<<std::endl; return 0; } A simple program that initializes a ten element integer array and prints all elements using for loop
  • 10. Array … Updating elements array[index] = new-value; A declared array element can be assigned a valid value during within the scope of array. See below: #include <iostream> int main(int argc, char** argv) { int values[10]={1,2,3,4,5,6,7,8,9,10}; values[2]=20; values[4]=30; values[9]=11; return 0; }
  • 11. Array … search an element Write down a small program using an array containing ten integer values (properly initialized). Input an integer value from user and search whether given value exists in array or not. Program:
  • 12. Array … Why we need it? It is often required during programming that some operation is required to be applied over set of fixed size data items e.g. search a specific item from a set of values, sum the values of list of numbers, initialize all quantities within a list with some given value etc To meet the situations above and many more, almost all programming languages support arrays or similar data structures Wherever we want to use multiple variables of same type of data, array can be very handy Array allows to declare and initialize multiple variables of same type using single statement Instead of apply some operation on individual items of same type, we can use a loop to do the same on an array (very convenient)
  • 13. Array … pros and cons Advantages Disadvantages It is used to represent multiple data items of same type by using only single name Insertion / deletion of elements is not straight forward and requires a lot of effort It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc. Most programming languages offer static arrays not allowing elements beyond defined boundaries Common mathematical models e.g. matrices, tables can be represented by 2D arrays Larger arrays may cause loss of memory i.e. whole memory is allocated even when few elements are availablel Elements can be accessed randomly Multi-dimension arrays are neither easier to implement nor to maintain Suitable data structure when elements are already known Few languages (C / C++) does not provide array boundary check introducing inappropriate access to application data One can use same name for a collection of similar elements We must know in advance that how many elements are to be stored in array
  • 14. character string as array In C/C++ strings are treated like as an array of characters e.g. char message[]=“welcome”; Above character is stored in memory like: w e l c o m e 0 Every string is terminated by a null character ‘0’
  • 15. character string as array … If we initialize a character array with a size e.g. char message[12] = “welcome”; Then memory actually looks like: Last four characters spaces are unused. w e l c o m e 0
  • 16. character string as array … We can actually access individual elements of a character array: char message[]=“welcome”; std:cout<<message[3]<<std:endl; Output: c
  • 17. character string as array … Creating a string as character array requires at compile time how many character will be stored in it. Such arrays are called static arrays. Examples below: char message[]=“message”; // eight characters will be allocated for this array char country[20]=“Pakistan”; // nine chracters will be allocated for this array
  • 18. Array name AND pointer Array name is a pointer and it points to initial position of memory allocated to store array contents. It can be assigned to a character pointer type of variable and that in return can access array contents like original array name. Example below: char message[]="welcome"; char *pointer=message; std::cout<<pointer[3]<<std::endl;
  • 19. Multi-dimensional arrays C/C++ allows multi-dimensional arrays. Following is the syntax for declaring them: datatype array_name[dim1][dim2]….[dimN]; A typical two dimensional integer array can be declared as: int arr[5][4]; This 2D array can be imagined as a table and can be visualized as: arr[0][0] arr[0][1] arr[0][2] arr[0][3] arr[1][0] arr[1][1] arr[1][2] arr[1][3] arr[2][0] arr[2][1] arr[2][2] arr[2][3] arr[3][0] arr[3][1] arr[3][2] arr[3][3] arr[4][0] arr[4][1] arr[4][2] arr[4][3] Row 0 Row 1 Row 2 Row 3 Row 4 Col 0 Col 3 Col 2 Col 1
  • 20. Multi-dimensional arrays A multi-dimensional array can be initialized by specifying each row values separated by commas as below: int arr[2][3]={{1,2,3}, {1,2,3}}; 1 2 3 1 2 3
  • 21. Exercise questions Q#01. Write down a function with following prototype: int find(data, target) where data is an integer array and target is an integer value. Find() searches through data and returns the index of value that is equal to target. It returns -1 if no elment in data is equal to target. Q#02. Write down a function with following prototype: int find(data, target) where data is an integer array and target is an integer value. Find() searches through data and returns the index of last occurance of value that is equal to target. It returns -1 if no elment in data is equal to target.
  • 22. Exercise questions Q#03. Write down a function with following prototype: int count(data, target) where data is an integer array and target is an integer value. Count() searches through data and number of occurances of target value within the data. It returns 0 if no elment in data is equal to target. Q#04. Write down a function with following prototype: void double(data) where data is an integer array. Double() updates all values within the data with double of its original values.
  • 23. Homework for next class Q#01. Write a function equal(data1, data2) as below: int equal(data1, data2) where both data1 and data2 are integer arrays. Equal() returns 1 if both arrays have same values and same order. It returns 0 otherwise. Example: If data1={1,2,3} and data2={1,2,3}, equal() returns 1 If data1={1,2,3} and data2={2, 1,3}, equal() returns 0 If data1={1,2,3} and data2={4,2,3}, equal() returns 0 If data1={1,2,3} and data2={1,2,3,4}, equal() returns 0 If data1={1,2,3} and data2={4,5,6}, equal() returns 0
  • 24. Homework for next class Q#01. Write a function equal(data1, data2) as below: int equal(data1, data2) where both data1 and data2 are integer arrays. Equal() returns 1 if both arrays have same values. It returns 0 otherwise. Example: If data1={1,2,3} and data2={1,2,3}, equal() returns 1 If data1={1,2,3} and data2={2, 1,3}, equal() returns 1 If data1={1,2,3} and data2={4,2,3}, equal() returns 0 If data1={1,2,3} and data2={1,2,3,4}, equal() returns 0 If data1={1,2,3} and data2={4,5,6}, equal() returns 0
  • 27. Course contents Linked List Linked List ADT Linked List Representation Linked List Operations (Idea & Implementation) PrintAll AddNode AppendNode InsertNode DeleteNode Size
  • 28. Linked Lists A finite and ordered sequence of items connected together through links is called a linked list or simply a list. Items in a linked list are generally called nodes A node in a linked list consists of two parts i. Data part ii. Link part Data part is for storage of value(s) and link part contains the address of simply another node of same list First node is commonly known as start node
  • 29. Linked Lists … A list object contains the reference to start node only First node is directly accessed by linked-list object and other nodes are accessed one by one using the links to other elements Since list nodes can only be accessed one by one sequentially, list data structure is also categorized as a linear data structure Linked List
  • 30. Linked Lists … List elements are ordered only in a sense that they can be accessed one by one beginning from start node (ordered does not mean sorted) A list is said to be empty if its start node points to NULL NULL is a special pointer that indicates the end of list First node of list (start node) is called the head and last node is called the tail List can grow and shrink dynamically (generally no limit on number of elements) When list grows, memory allocated for it also grows i.e. memory allocated for list directly refers to number of nodes in the list
  • 31. ADT An abstract data type (ADT) is a mathematical model for data types where a data type is defined by its behavior (semantics) from the point of view of a user of the data, specifically in terms of possible values, possible operations on data of this type, and the behavior of these operations. https://en.wikipedia.org/wiki/Abstract_data_type
  • 32. Linked list ADT Note: More operations can be defined as per needs.
  • 33. Linked list ADT … Node operations Operation Description Node(int) Construtor that initializes node ‘data’ members with given value & node pointer ‘next’ to NULL void Set_data(int) Sets the data member ‘data’ with provided value int get_data() Returns current value of ‘data’ void set_next(Node*) Sets the data member ‘next’ with provided ‘pointer’ Node* get_next() Returns the current value of ‘next’ pointer
  • 34. Linked list ADT … linklist operations Operation Description Pseudo Code LinkList() A constructor that initializes data member ‘start’ to NULL  Assign NULL to ‘start’ size() A method that returns the size of Linked List i.e. number of elements in it  Take a temprorary node pointer ‘temp’ and point it to ‘start’ node pointer  Set ‘count’ to zero  It traverses all nodes one by one by pointing ‘temp’ pointer to ‘next’ pointer and increasing the ‘count’ by one in every iteration  Iterations stop when ‘temp’ points to NULL address  At this point value of ‘count’ is returned
  • 35. Linked list ADT … linklist operations Operation Description Pseudo Code print_all() Prints the ‘data’ values for all nodes in Linked List  Take a temprorary node pointer ‘temp’ and point it to ‘start’ node pointer  It traverses all nodes one by one by printing value of ‘data’ for node ‘temp’ is pointing to and then pointing ‘temp’ to ‘next’ pointer  Iterations stop when ‘temp’ points to NULL value
  • 36. Linked list operations … print all
  • 37. Linked list operations … add node Operation Description Pseudo Code add_node(key) Adds a new node to start of list  Creates a new node ‘temp’ with provided ‘key’ as ‘data’ value  Points ‘next’ pointer to ‘start’  Moves ‘start’ to ‘temp’
  • 38. Linked list operations … append node Operation Description Pseudo Code append_node(key) Adds a new node to end of list  Create a new node ‘n’ using given ‘key’ as its ‘data’ and NULL as ‘next’ pointer  Creates a node pointer ‘temp’ and point it to start  If ‘temp’ points to NULL, assign ‘n’ to ‘start’  Otherwise, traverse ‘temp’ to the last nodes of list using ‘next’ pointers of intermediate nodes  Assign ‘n’ to ‘next’ of ‘temp’
  • 39. Linked List operations … append node
  • 40. Linked List operations … search node Operation Description Pseudo Code Search_node(key) Searches node from list whose ‘data’ value is equal to ‘key’ provided and returns its reference  Take a node pointer ‘temp’ and point it to ‘start’  Iterate ‘temp’ through list nodes until either a node with ‘data’ equal to ‘key’ is found or list ends (‘temp’ points to NULL)  Return the node pointer ‘temp’ is pointing to
  • 41. Linked List operations … search node No node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure ‘NULL’ value is return as response
  • 42. Linked List operations … search node Node in Linked List having ‘data 4’ as its value same as of ‘key’ Pointer to ‘data 4’ is returned as response
  • 43. Linked List operations … insert node Operation Description Pseudo Code insert_node(after, key) Inserts a new node into Linked List after a node with given value  Call the search(after) procedure as described earlier  If Node pointer returned as above call is equl to NULL, insertion not possible  Otherwise (a valid node pointer is returned say ‘temp’), create a new node ‘n’  Set ‘key’ to the ‘data’ of ‘n’ and set ‘next’ of ‘temp’ to ‘next’ of ‘n’
  • 44. Linked List operations … insert node A new node needs to be deleted after ‘data2’
  • 45. Linked List operations … append node Operation Description Pseudo Code Append_node(key) Adds a new node to end of list  Create a new node ‘n’ using given ‘key’ as its ‘data’ and NULL as ‘next’ pointer  Creates a node pointer ‘temp’ and point it to start  If ‘temp’ points to NULL, assign ‘n’ to ‘start’  Otherwise, traverse ‘temp’ to last nodes using ‘next’ pointers of intermediate nodes  Assign ‘n’ to ‘next’ of ‘temp’
  • 46. Linked List operations … delete node Operation Description Pseudo Code delete_node(key) Deletes node from list whose ‘data’ value is equal to ‘key’ provided. List remains in tact after delete operation has executed  Take a node pointer ‘temp’ and point it to ‘start’  Iterate ‘temp’ through list nodes until either a node with matching ‘data’ is found or list ends  If list has ended, nothing happens  If node with ‘data’ equal to ‘key’ was found at ‘start’, ‘start’ pointer starts pointing to its ‘next’ node  If node with ‘data’ equal to ‘key’ was found after ‘start’, list pointers are adjusted and that node is removed from list
  • 47. Linked List operations … delete node No node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure Linked List remains same, nothing happens
  • 48. Linked List operations … delete node ‘start’ node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure ‘start’ pointer points to next node in list, matching node is removed from list
  • 49. Linked List operations … delete node A node in Linked List after ‘start’ had same value of ‘data’ as of ‘key’ provided to procedur Linked List remains intact with ‘data 3’ node removed
  • 50. Linked List Operations … C++ Code Create two classes i. Node ii. LinkList as their ADT Node class is simple it just contains two data members i. data (int data type for simplicity) ii. next (Node pointer) for pointing to next node in list Create public constructor for Node class Create setters and getters for Node data members Node class code is all set
  • 51. Linked List Operations … node class class Node { int data; Node* next; public: Node(){data=0;next=0;}; void set_data(int d){this->data=d;}; int get_data(){ return this->data; }; void set_next(Node *n){this->next=n;}; Node* get_next(){return this->next;}; };
  • 52. Linked List Operations … C++ Code Create class LinkList with a single data member i. start (a node pointer) pointing to head node of Linked List Define constructor and operations as discussed earlier Selected operations code is given as: Note: implement yourself remaining function belonging to LinkList class
  • 53. Linked List Operations … linklist class class LinkList{ Node* start; public: LinkList(); void add_node(int); void append_node(int); int size(); Node* search(int); void delete_node(int); void insert(int, int); void print_all(); };
  • 54. Linked List Operations … linklist class LinkList :: LinkList() { this->start = 0; } void LinkList::add_node(int key) { Node* n=new Node(); n->set_data(key); n->set_next(this->start); this->start = n; }
  • 55. Linked List Operations … linklist class int LinkList::size() { int count = 0; Node *temp = this->start; while(temp) { count++; temp = temp->get_next(); } return count; }
  • 56. Linked List Operations … linklist class Node* LinkList::search(int key) { Node *temp = this->start; while(temp && temp->get_data()!= key) { temp = temp->get_next(); } return temp; }
  • 57. Linked List Operations … main method int main(int argc, char** argv) { LinkList list; list.add_node(2); list.append_node(10); list.add_node(7); list.insert(3,25); list.print_all(); list.delete_node(30); list.print_all(); return 0; }
  • 58. Structure of Link List Struct{ Int data; Struct node * link ; }; Struct node * ptfirst = null; (null = 0)
  • 59. Main Algorithm Start Repeat (loop) while true (true = 1) [menu option] Write(cout) (“1: Insert ”); Write (“2: display ”); Write (“3: Insert first ”); Write (“4: Insert after ”); Write (“5: Insert before ”); Write (“6: Delete ”); Write (“7: Exite ”); Write (“Enter option number ”); Read (cin) option number (option_number) Select option_number It include switch case Option 1 Write (“ Insert value ”); Read value Insert (value) Option 2
  • 60. Insert (value) [check for empty list] If ptfirst == NULL ; then Temp = new node ; Temp -> link = ptfirst; Ptfirst = temp; Else Ptfirst = temp ; Repeat while loop (temp != NULL) Temp = temp -> link; [End of loop of step 2a] Temp-> link = new node ; Temp = temp -> link ; [End of if-else structure ] Temp -> data = value; Temp -> link = NULL;
  • 61. Display(); if ptfirst == NULL then write(“list is empty”); return [End of if structure ] temp = ptfist; repeat while (temp != NULL) ◦ write (temp -> data) ◦ Temp -> temp -> link ; [End of loop] return ; Algorithm for inset first Insert first(value) [creat a new node ] Temp = new node; Temp -> data = value; Temp -> link = ptfirst; Ptfirst = temp; Return;