Algorithm Chapter Three
Algorithm Chapter Three
Injibara University 1
Pointer
o A pointer is simply the address of
2 a memory location and provides
example:
5/31/2021
o Common uses pointers:
5/31/2021
Reference Operator (&)
that variable.
5/31/2021
// demo of the reference operator
int main()
0x6aff04
{ 0x6aff00
int var1=10,var2=20,var3=30; 0x6afefc
cout<<endl<<&var1<<endl<<&var2<<endl<<&var3; 10
cout<<endl<<var1<<endl<<var2<<endl<<var3; 20
30
return 0;
5/31/2021
Deference operator ( *)
o Pointers are said to "point to" the variable whose reference they store
7
value stored in the variable which it points to.
Value = *Ptr;
5/31/2021
Declaring Pointer Variables
8
o A variable name directly references a value, and a pointer indirectly
references a value.
o Pointers, like any other variables, must be declared before they can
be used.
datatype *var-name;
o The type of data that a pointer will point to is determined by its base
type
asterisk(*).
5/31/2021
//demo for pointer addresss and data value
#include<iostream.h>
int main()
9
{
int a = 100;
int *p = &a;
cout << a << " " <<endl; //values of a
cout<< &a <<endl; //addres of variable a
cout << p << " " <<endl; // pointer values
cout<< &p <<endl; //address of pointer
cout<<*p<<endl; //holds values a pointed by pointer
return 0;
}
5/31/2021
Example
o Int *a,*b,*c;
// 'x' and 'z' are pointers, but 'y' is an ordinary long variable.
5/31/2021
//demonstrations of pointer
#include<iostream.h>
void main()
11
{
float *p;
float a = 9;
float b = 4;
p = &a;
cout << p << endl; // The address of a
cout << *p << endl; // The value of a
*p *= 4; // Multiply 'a' by 4
p = &b;
cout << p << endl; // The address of b
cout << *p << endl; // The value of b
*p += 10; // Add 10 to 'b„
cout << a << endl; // Display new value of 'a„
cout << b << endl; // Display new value of 'b'
return 0;
}
5/31/2021
Pointers and functions
o Pointers used to pass value from 12
calling program to a function.
//demonstration of pointer function int num1, num2;
#include<iostream.h>
cout << "Enter first number" << endl;
void swap( int *a, int *b )
{ cin >> num1;
int t; cout << "Enter second number" << endl;
t = *a;
cin >> num2;
*a = *b;
*b = t; swap( &num1, &num2);
} cout << "First number = " << num1 << endl;
}
5/31/2021
Array pointers
o The name of an array points only to the first element not the whole
array
5/31/2021
//array pointer demonstrations
#include<iostream.h> Con’t
#include<math.h> 14
int main() {
int n[] = { 10,20,30,40,50,60};
int *ptr = n;
cout<<"\n Displaying array contents using array\n ";
for(int i=0; i<6; i++) {
cout<<n[i]<<" "; //using array
}
cout<<"\n Displaying array contents using pointer\n ";
for(ptr= &n[0]; ptr<=&n[5]; ptr++)
{
//cout<<*(ptr+i) <<" ";
cout<<*ptr<<" "; // using pointer
}
return 0;
} 5/31/2021
NULL pointer
15
o NULL is a special value that indicates an empty pointer
displayed result
int *p;
p = 0;
cout << p << endl; //prints 0
cout << &p << endl;//prints address of p
cout << *p << endl;// not display output value
5/31/2021
Structure
o An abstract data type is an abstract
16 description of a data structure, with
the emphasis on its properties functionality and use rather than specified
implementation is referred to as ADT.
o These data elements, known as data members, can have different types
o There are two broad types of data structure based on their memory
allocation:
Injibara University 17
Declaration of Structure
o Structure is a collection of data items and the data items can be of different
data type and the data item of structure is called member of the structure.
o Structure is defined using the struct keyword.
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
…..
data type n member n;
};
o structure_name is a name for the structure type, object_name can be a set of
valid identifiers for objects that have the type of this structure.
o Within braces { } there is a list with the data members, each one is specified
with a type and a valid identifier as its name.
5/31/2021
o Example: The follow defines a structure called „date‟ which contains
three „int‟ member variables: „day‟, „month‟, and „year‟:
struct date
{
string day;
int month;
int year;
};
o Its possible to define in all in if data types are similar.
struct date
{
string day;
int month, year;
};
o The struct keyword creates a new user defined data type that is used to
declare variable of an aggregated data type.
5/31/2021
Declaring using sturct data types
o Once you have defined a structure you can create a variable from it just as
student std1;
date birthday;
int i;
o The above statements are similar in nature because both declare a variable
of a given type.
o The former is a built in type, which is integer while the later declares a
5/31/2021
Initializing Structure Variables
o Values are assigned to member
21 variables in the order that they
occur.
o For example:
5/31/2021
Accessing members of a structure variable
structure_name.datamember;
o Example: For reading and displaying values to and from structure s1.
5/31/2021
//example to demonstrate structure
#include <iostream.h>
struct date {
int day, month, year;
};
int main() {
date birth;
cout << “Enter your birth date: ” << endl;
cout << “Year: “;
cin >> birth.year;
cout << “Month: “;
cin >> birth.month;
cout << “Day: “;
cin >> birth.day;
cout << “You entered “ << birth.month << “/”<< birth.day << “/” << birth.year << endl;
cout << “You were born in the “<< ((birth.year / 100) + 1) << “th Century!”<< endl;
return 0;
} 5/31/2021
Array Structure
#include<iostream.h> cout<<"\nEnter Name";
struct student cin>>s[i].name;
{
}
int id;
cout<<"\n Displaying student Info";
char name[15];
cout<<"\nStudent Id \t Student Name";
}; cout<<"\n===================";
int main()
for( i = 0; i < 5; i++)
{
cout<<endl
//creating 5 student using an array
cout<<s[i].id<<"\t\t\t"<<s[i].name;
student s[5];
return 0;
int i;
}
for(i=0; i < 5; i ++)
{
cout<<"\n Enter Student Id";
cin>>s[i].id;
5/31/2021
Pointers to Structure
o Pointers are variables that store address of other variables.
Student *Std;
Student Abebe;
Std = &Abebe;
o The value of the pointer std would be assigned to a reference to the object
Abebe (its memory address)
25
Injibara University
o The arrow operator (->) or deference operator is used exclusively
with pointers to objects with members.
o It serves to access a member of an object to which we have referenced.
i.e. To access a member through a pointer, we append its name to the
pointer‟s name separated by arrow
Std->age; is equivalent to (*std).age;
o Both are to mean, we are accessing age member variable of structure
pointed by a pointer called std.
o But *(std.age) which is equivalent to *std.age it mean that it evaluate value
pointed by member variable age of object std
Injibara University 26
//pointer structure demonstrations
#include <iostream.h>
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
ptr = &d;
cout << "Enter feet: ";
cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;
cout << "Displaying information." << endl;
cout << "Distance = " <<(*ptr).feet <<"feet = " << (*ptr).inch << " inches";
return 0;
} Injibara University 27
//pointer structure demonstrations structure name Distance
#include <iostream.h>
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
ptr = &d;
cout << "Enter feet: ";
cin >> ptr->feet;
cout << "Enter inch: ";
cin >>ptr->inch;
cout<<"Displaying information."<<endl;
cout<<"Distance = "<<ptr->feet<<"feet = "<<ptr->inch<<" inches";
return 0;
}
Injibara University 28
Self-Referential structures
o A structure declaration cannot contain itself as a member, but it can contain a
member which is a pointer whose type is the structure declaration itself .
o A self referential structure is used to create data structures like linked lists,
stacks, queue, trees and graphs.
o A self-referential structure is one of the data structures which refer to the pointer
to (points) to another structure of the same type
struct node
{
int val;
int left;
struct tree *right;
};
o „right‟ is a pointer to a structure of type „tree‟ and the structure „node‟
is a self-referential structure with „right‟ as the referencing pointer.
Injibara University 29
o There are two types of self referential Structures.
Injibara University 30
2. Self Referential Structure with multiple Links
o Self referential structures with multiple links can have more than one
self-pointers.
o Many complicated data structures can be easily constructed using these
structures.
o Such structures can easily connect to more than one nodes at a time.
o The following example shows one such structure with more than one
links.
Injibara University 31
Linked List Structure
o Linked lists are the most basic self-referential structures that allow to
have a chain of structs with related data.
o If a node of linked list structure has a link only to its successor in the
sequence of node, the list is called a single linked list.
Injibara University 32
o A linked list is made up of a chain of nodes and each node contains
data item and a pointer to the next node for single list.
o Start (Head) is a pointer to first node and Last (terminal) node contain
null pointer which is a pointer, what ever its type, can point to any.
o Linked list is a very flexible dynamic data structure items may be added
to it or deleted from it at will.
o As items are added to a list, memory for a node is dynamically allocated.
Injibara University 33
o Link - Each Link of a linked list can store a data called an element
o Next - Each Link of a linked list contain a link to next link called Next.
o Linked List - A Linked List contains the connection link to the first Link
called First
– Circular Linked List - Last item contains link of the first element as
next and first element has link to last element as prev.
Injibara University 34
Creating linked list
o A linked list is a data structure that is built from structures and pointers.
Struct Node
{
datatype data;
Node * next; // pointer to next node in the list
};
o When a program creates a linked list, it usually starts with an empty list.
o A new node is dynamically allocated from the free store using the new
operator, and the desired information is copied into it.
Injibara University 35
o A newly created node is linked to the list by rearranging the pointers.
o Thus linked list does not have to have a predetermined size.
o Example: Node *NodeName = new Node
Time1 * T1 = new Time1
Student *Abebe = new student
o Head, variable that holds a pointer to the first node of the list, is set to null
when the list is empty.
Injibara University 36
o Adding a node to the list: Steps
– Allocate a new node.
– Set the node data values and make new node point to NULL.
– Make old last node‟s next pointer point to the new node.
– * Make the new last node‟s prev pointer point to the old last node.
(This is only for Double Linked list).
Injibara University 37
Linked list Traversal
o A procedure that access and processes all elements of a data
structure in sequence is called traversal.
o Traversing through the linkedlist
To Move Forward
– Set a pointer to point to the same thing as the start (head) pointer.
– If the pointer points to NULL, display the message “list is
empty" and stop.
– Otherwise, move to the next node by making the pointer point to
the same thing as the next pointer of the node it is currently
indicating.
Injibara University 38
To Move Forward: (Double linked list)
– If the pointer points to NULL, display the message “list is empty" and stop.
– Set a new pointer and assign the same value as start pointer and move
forward until you find the node before the one we are considering at the
moment.
– Set a pointer to point to the same thing as the end (tail) pointer.
– If the pointer points to NULL, display the message “list is empty" and stop.
– Otherwise, move back to the previous node by making the pointer point to
the same thing as the prev pointer of the node it is currently indicating.
Injibara University 39
Display the content of list: Steps
– Set a temporary pointer to point to the same thing as the start pointer.
– If the pointer points to NULL, display the message "End of list" and
stop.
– Otherwise, display the data values of the node pointed to by the start
pointer.
– Make the temporary pointer point to the same thing as the next pointer
of the node it is currently indicating.
– Jump back to step 2.
Injibara University 40
Injibara University 41
Inserting at the End : Steps
– Allocate a new node.
– Set the node data values and make the next pointer of the new node point to
NULL.
– Make old last node‟s next pointer point to the new node.
– Update end to point to the new node.
Insertion in the middle: Steps
– Create a new Node
– Set the node data Values
– Break pointer connection
– Re-connect the pointers
Injibara University 42
43
Singly linked list
o Start (Head): Special pointer that points to the first node of a linked
list, so that we can keep track of the linked list.
– The last node should points to NULL to show that it is the last link
in the chain (in the linked list).
Injibara University 44
It is the singly linked list which has four nodes in it, each with a
link to the next node in the series (in the linked list).
Injibara University 45
It can grow or shrink in size during execution of a program.
struct node
int data;
node *next;
};
– Deleting any node using the search data from a singly linked list
– Display the node from the singly linked list in a forward manner
int main()
insertEnd(10);
insertEnd(12);
cout<<endl;
ForwardDisplay();
return 0;
Injibara University 48
o Adding a node to the end of a singly linked list
void insertEnd(int x)
{
node *temp=new node;
temp->data=x;
temp->next=NULL;
if(head==NULL)
head = temp;
else
{
node *temp2 = head;
while(temp2->next!=NULL)
{
temp2 = temp2->next;
}
temp2->next= temp;
}
}
Injibara University 49
o Adding a node to the front of a singly linked list
void insertFront(int x) {
temp->data=x;
temp->next=NULL;
if(head==NULL)
head = temp;
else {
temp->next = head;
head = temp;
} Injibara University 50
o Adding a node to the right of a specific value in a singly linked list
Injibara University 52
o Deleting a node from the front of a singly linked list
void deleteFront()
{
node *temp;
if(head==NULL)
cout<<"No data inside\n";
else
{
temp = head;
head = head->next;
delete temp;
}
}
Injibara University 53
o Deleting a node from the end of a singly linked list
void deleteEnd()
{
node *temp, *temp3;
if(head==NULL)
cout<<"No data inside\n";
else
{
temp = head;
while(temp->next!=NULL)
{
temp3 = temp;
temp = temp->next;
}
temp3->next = NULL;
delete temp;
}
Injibara University 54
}
o Deleting a node of specific data of a singly linked list
void deleteData(int x) {
{ temp = head;
if(head==NULL) {
{ }
delete temp; }
} }
else
Injibara University 55
o Display in a forward manner in a singly linked list
void ForwardDisplay()
{
node *temp;
if(head==NULL)
cout<<"No data inside\n";
else
{
temp = head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp = temp->next;
}
}
}
Injibara University 56
o Creating Empty List
o Each node points not only to Successor node (Next node), but also to
Injibara University 59
o Node- contains reference to the next node and the previous node in the linked
list and contains data that is associated with the current node.
o Link - Each Link of a linked list can store a data called an element.
o Next - Each Link of a linked list contain a link to next link called Next.
o Prev - Each Link of a linked list contain a link to previous link called Prev.
o There are two NULL: at the first and last nodes in the linked list.
Injibara University 60
o Operations of Doubly Linked List
– Deleting any node using the search data from a doubly linked list
– Display the node from the doubly linked list in a forward manner
– Display the node from the doubly linked list in a backward manner
Injibara University 61
Creating double Linked lists
o Nodes for a doubly linked list would be defined as follows:
struct node
{
int data;
node *prev;
node *next;
};
node *head = NULL, *tail = NULL;
o Example:
struct node
{
char name[20];
node *nxt; // Pointer to next node
node *prv; // Pointer to previous node
}; Injibara University 62
o Adding a node to the end of a doubly linked list
void insertEnd(int x) {
{ tail->next = temp;
node* temp = new node; temp->prev = tail;
temp->data = x; tail = temp;
temp->next = NULL; }
temp->prev = NULL; }
if (head == NULL)
head = tail = temp;
else
Injibara University 63
o Adding a node to the front of a doubly linked list
{ {
temp->prev = NULL; }
if(head == NULL) }
Injibara University 64
o Adding a node to the left of a specific data in a doubly linked list
void insert_left_y(int x, int y) else
{ {
node* temp = new node; node *temp2 = head, *temp3;
temp->data = x; while(temp2->data!=y)
temp->next = NULL; {
temp->prev = NULL; temp3 = temp2;
if (head == NULL) temp2 = temp2->next;
head = tail = temp; }
else temp->next = temp3->next;
if(head->data==y) temp3->next = temp;
{ temp->prev = temp3;
temp->next = head; temp2->prev = temp;
head->prev = temp; }
head = temp; }
}
Injibara University 65
o Adding a node to the right of a specific data in a doubly linked list
void insert_right_y(int x, int y) }
{ else
node* temp = new node; {
temp->data = x; node *temp2 = head;
temp->next = NULL; while(temp2->data!=y)
temp->prev = NULL; {
if (head == NULL) temp2 = temp2->next;
head = tail = temp; }
else if(temp2->next==NULL)
if(head->data==y) tail = temp;
{ temp->prev = temp2;
if(head->next==NULL) temp->next = temp2->next;
tail = temp; temp2->next->prev = temp;
temp->prev = head; temp2->next = temp;
temp->next = head->next; }
head->next->prev = temp; }
Injibara University 66
head->next = temp;
o Deleting a node from the end of a doubly linked list
void deleteEnd()
{
node *temp;
if(tail==NULL)
cout<<"No data inside\n";
else
{
temp = tail;
tail = tail->prev;
tail->next = NULL;
delete temp;
}
}
Injibara University 67
o Deleting any node using the search data from a doubly linked list
void deleteEnd(int x)
{
if(head==NULL)
cout<<"No data inside\n";
else
{
node *temp = head, *temp2;
while(temp->data!= x)
{
temp2 = temp;
temp = temp->next;
}
temp2->next = temp->next;
temp->next->prev = temp2;
delete temp;
}
}
Injibara University 68
o Display the node from the doubly linked list in a forward manner
void dispalyForward()
{
node *temp;
if(head==NULL)
cout<<"No data inside\n";
else
{
temp = head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp = temp->next;
}
}
}
Injibara University 69
o Display the node from the doubly linked list in a backward manner
void dispalyBackward()
{
node *temp;
if(tail==NULL)
cout<<"No data inside\n";
else
{
temp = tail;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp = temp->prev;
}
}
} Injibara University 70
Summary on array and linked list
o Arrays
– possible to access random elements
– It is possible to traverse forward and backward
o Limitation
– We do not always know in advance the exact number of elements an array
needs to store
– It is impossible to add an elements at the beginning or last (not flexible )
– Much of the memory may not be used
o Linked list
– Overcome the problem of arrays
– An element can be inserted or deleted easily from linked list
– No memory is wasted for vacant nodes
o Limitation
– It is sequential access by its nature
– Need extra memory to store pointers to nodes
Injibara University 71
Stack Data Structure
Injibara University 72
Stack
o Stack is a data structure provides temporary storage in such a way that the
o It has a LIFO (Last In First Out) or FILO (First In Last Out) structure.
o Items can be inserted (“pushed”) and deleted (“popped”), but only the
o Stack is useful for temporary storage for dealing with nested structure;
– Only the last element added onto the stack (the top element) can be
accessed or removed.
Injibara University 74
Stack operations
o push(k): push(put) an item k into stack s and Its insertion operation into
stack
o pop(): deleting the top element of the stack s, and returning its value.
Note:- The operations of insertion and deletion are called PUSH and POP
respectively.
Injibara University 75
o Algorithms for the basic operations:-
createStack()
{
remove existing items from the stack
initialise the stack to empty
}
push( k) pop()
{ {
if there is room in the stack s if the stack s is not empty
put item k on the top of the stack return the value of the top item
else remove the top item from the stack
give an error message decrease index of the top element
} else
give an error message
}
Injibara University 76
Example:- (TOS = Top Of Stack)
Injibara University 77
o Stacks in computer science
The stack is one of the most important data structures in all of computer science
– Function/method calls are placed onto a stack.
– Compilers use stacks to evaluate expressions.
– Stacks are great for reversing things, matching up related pairs of things, and
backtracking algorithms.
o Stack programming problems
– Reverse letters in a string, reverse words in a line, or reverse a list of numbers.
– Find out whether a string is a palindrome. (Example: madam, lol, pop, radar)
– Examine a file to see if its braces { } and other operators match.
o Stack Application
– Reversing data
– Converting decimal to binary
Injibara University 78
Stack implementations using Array
int f = - 1, r = - 1, s[50], n = 50;
o A stack can be implemented a static and dynamic data structure.
o When we say a static, it is using array and when we say dynamic, it
is using linked list.
o Stack has at least the following operation:
– push an element to the top of the stack
– pop an element from the top of the stack
– display the content of the top element in the stack
– display the content of all elements in the stack forward manner
– display the content of all elements in the stack backward manner
Injibara University 79
o Push an element to the top of the stack in an Array
void push()
{
int val;
if(r==n-1)
cout<<"Stack Overflow"<<endl;
else
{
if(f==-1)
f=0;
cout<<"Insert an element to push : "<<endl;
cin>>val;
r++;
s[r] = val;
}
}
Injibara University 80
o pop an element from the top of the stack in an array
void pop()
{
if(f==-1||f>r)
{
cout<<"Stack Underflow ";
return; //exist if the condition is true
}
else
{
cout<<"Element popped off from stack is : "<<s[r]<<endl;
r--;
}
}
Injibara University 81
o Display the content of the top element in the stack in an array
void displayTop()
{
if(f==-1)
cout<<"Stack is empty"<<endl;
else
{
cout<<"The top element in the Stack is : ";
cout<<s[r]<<" ";
cout<<endl;
}
}
Injibara University 82
o Display the content of all elements in the stack forward manner in
an array
void displayForward()
{
if(f==-1)
cout<<"Stack is empty"<<endl;
else
{
cout<<"Stack elements are : ";
for(int i=f;i<=r;i++)
cout<<s[i]<<" ";
cout<<endl;
}
}
Injibara University 83
o Display the content of all elements in the stack back manner in an
array
void displayBackward()
{
if(r==-1)
cout<<"Stack is empty"<<endl;
else
{
cout<<"Stack elements are : ";
for(int i=r;i>=f;i--)
cout<<s[i]<<" ";
cout<<endl;
}
}
Injibara University 84
Stack implementations using linked list
Injibara University 85
o Linked list implementation uses a single linked list with elements
added and removed at one end head or tail of the list
Injibara University 89
o Display the content of all elements in the stack in a forward manner in
a linked list
{ }
temp = head; }
}
Injibara University 90
o Display the content of all elements in the stack in a backward manner in a
linked list
{ {
else }
{ }
temp = tail;
Injibara University 91
Applications of Stacks
o Each time a function call occurs whether it is recursive function or not the
return address in the calling function is saved.
o If stored in a fixed memory area then the function can not be repeatedly
called because first return address would be overwritten by the second
return address before the first used.
Injibara University 92
o Main function call F and F call G and H that must be first completed
before F then F before main function.
o Hence G and H contain calling function address (return address) of F
Injibara University 93
Applications of stacks Con’t
o For evaluation of Algebraic Expressions
– Example: 4 + 5 * 5
simple calculator: 45
– Priority 2: / *
– Priority 1: + -
Injibara University 96
Example : Convert the following infix expression to postfix notation
A+B*C-D/E
Move Current Token Stack Bottom:> Postfix
1 A empty A
2 + + A
3 B + AB
4 * +* AB
5 C +* ABC
6 - + ABC*
7 - empty ABC*+
8 - - ABC*+
8 D - ABC*+D
9 / -/ ABC*+D
10 E -/ ABC*+DE
11 empty - ABC*+DE/
12 empty ABC*+DE/-
97
Injibara University
Example: Convert A * (B + C) * D to postfix notation.
Injibara University 98
Example:- Consider the infix expression
6523+8*+3+*
o If an item in the list is a number( an operand), it is pushed into the stack
o If the item in the list is an operator, two numbers are popped up and
their result is pushed back into the stack.
o The first item is a value (6) so it is pushed onto the stack
The next item is a value (5) so it is pushed onto the stack
The next item is a value (2) so it is pushed onto the stack
The next item is a value (3) so it is pushed onto the stack
o The remaining items are
+8*+3+*
Injibara University 99
o So next a '+' is read (a binary operator), so 3 and 2 are popped from
the stack and their sum '5' is pushed onto the stack:
o Next is operator *.
o so 48 and 6 are popped, and
6*48=288 is pushed
o Next is operator +.
o So 3 and 45 are popped and
45+3=48 is pushed
4 2 2 3 5 6
5 + 5 5 6
6 8 8 5 5 6
7 * 40 5 6
8 + 45 6
9 3 3 45 6
10 + 48 6
11 * 288
???