You are on page 1of 104

Chapter Three

Pointer and Structure

Compiled by:Nigusu Y. (nigusu02@gmail.com)

Injibara University 1
Pointer
o A pointer is simply the address of
2 a memory location and provides

an indirect way of accessing data in memory.

o A pointer variable is defined to „point to‟ data of a specific type. For

example:

int *ptr1; // pointer to an int

char *ptr2; // pointer to a char

o The value of a pointer variable is the address to which it points. For

example, given the definitions

int num; //can be written as ptr1 = #


5/31/2021
o A pointer is a variable used for storing the address of a memory cell
and use the pointer to reference this
3 memory cell

5/31/2021
o Common uses pointers:

 Accessing array elements

 Passing arguments to a function when the function needs to

modify the original argument

 Passing arrays and strings to functions

 Obtaining memory from the system

 Creating data structures such as linked lists

5/31/2021
Reference Operator (&)

o The address that locates a variable


5 within memory is a reference to

that variable.

o This reference to a variable can be obtained by preceding the

identifier of a variable with an ampersand sign (&), known as


reference operator, and which can be literally translated as "address
of".
ptr = &Var;

//Ptr now holds the address of the variable ‟var‟

5/31/2021
// demo of the reference operator

//This program prints the addresses of the three variables.


6
#include<iostream.h>

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.

o The pointer's identifier with an asterisk (*), which acts as dereference

operator and that can be literally translated to "value pointed by".

Value = *Ptr;

// read as: "Value equals to value pointed by Ptr"

o & is the reference operator and can be read as "address of"


o * is the dereference operator and can be read as "value pointed by"
o A variable referenced with (&) can be dereferenced with (*).

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

o Each variable being declared as a pointer must be preceded by an

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 double* first, second, third;

// 'first' is a pointer 'second' and 'third' are ordinary variables.

o Int *a,*b,*c;

// All these variables are pointers to int values.

o long *x, y, *z;

// '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;

cout << "Second number = " << num2 << endl;


int main()
{ return 0;

}
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

o If you try to access a NULL pointer, you will get an error or no

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 A structure is a group of data elements grouped together under one name.

o These data elements, known as data members, can have different types

and different lengths.

o There are two broad types of data structure based on their memory

allocation:

 Static Data Structures

 Dynamic Data Structure


5/31/2021
o Static Data Structures

– A data structures that are defined & allocated before execution,


thus the size cannot be changed during time of execution.

Example: Array implementation of ADTs.

o Dynamic Data Structure

– A data structure that can grow and shrink in size or permits


discarding of unwanted memory during execution time.

Example: Linked list implementation of ADTs.

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

you would any other variable.

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

variable type of user-defined type.

o std1 will have the characteristics of representing id and name of a student.

5/31/2021
Initializing Structure Variables
o Values are assigned to member
21 variables in the order that they

occur.

o For example:

date birthday = { 19, 8, 1979 };

student std1={"Abebe", "ETR/390/04",Male”,3.25};

student std2={"Fikir", "ETR/410/04",Female”,3.0};

student std3={"Rahel", "ETR/420/04",Female”,3.75};

5/31/2021
Accessing members of a structure variable

o The Dot operator (.): to access data


22 members of structure variables.

structure_name.datamember;

o Example: For reading and displaying values to and from structure s1.

cin>>s1.id; //storing to id item of s1

cin>>s1.name; //storing a name to s1

cout<<s1.id; //displaying the content of id of s1.

cout<<s1.name; //displaying name

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.

o A structure is a user defined data type which is essentially


a collection of variables of different types under a single name.

o A structure pointer is a type of pointer that stores the address of a


structure typed variable.

o Example: Pointer structure

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.

1. Self Referential Structure with Single Links

o These structures can have only one self-pointer as their member.

o The following example will show us how to connect the objects of a


self-referential structure with the single link and access the
corresponding data members.

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 Linked list structure is a collection of nodes storing data and links to


other nodes.

o A node contains some information useful for a specific application and


a pointer to the next node.

o The most flexible implementation is by using pointers

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

 Types of Linked List

– Single Linked List - Item Navigation is forward only.

– Doubly Linked List - Items can be navigated forward and backward


way.

– 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.

o It forms a chain of "nodes" with pointers representing the links of the


chain and holding the entire thing together

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.

Node *head = 0; // Declare empty list

o Head point to the first node in the list.

Head -> next; // point to the second node


o If nodeptr is a variable of the Node * data type and nodeptr points to a
node in our list, then the value of nodeptr-> next is the pointer to the next
node or it is null if there is no next node.

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)

– Set a pointer to point to the same thing as the start pointer.

– 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.

 To Move Backward: (Double linked list)

– 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.

 Insert at the front (beginning):steps


– Allocate a new node.
– Insert new element values.
– Make the next pointer of the new node point to old head (start).
– Update head (start) to point to the new node.

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).

 A node‟s successor is the next node in the sequence

 The last node has no successor

 A node‟s predecessor is the previous node in the sequence

 The first node has no predecessor

o A linked list‟s length is the number of elements in it

 A list may be empty (contain no elements), if the head points to


null.

Injibara University 45
 It can grow or shrink in size during execution of a program.

 It can be made just as long as required.

o Creation of singly linked list

struct node

int data;

node *next;

};

node *head = NULL;


Injibara University 46
o Operations of singly Linked List
– Adding a node to the end of a singly linked list

– Adding a node to the left of a specific data in a singly linked list

– Adding a node to the right of a specific data in a singly linked list

– Deleting a node from the end of a singly linked list

– Deleting a node from the front of a singly linked list

– Deleting any node using the search data from a singly linked list

– Display the node from the singly linked list in a forward manner

– size( ): Tells number of items/nodes in the list

– isEmpty( ): Checks if the list is empty


Injibara University 47
//main function

int main()

insertEnd(10);

insertEnd(12);

ForwardDisplay(); //display the data in forward manner

cout<<endl;

insertEnd(25); //insert data to the linkedlist

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) {

node *temp=new node;

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

void insert_right_y(int x, int y) node *temp2 = head;


{ while(temp2->data!=y)
node *temp=new node; {
temp->data=x; temp2 = temp2->next;
temp->next=NULL; }
if(head==NULL) temp->next = temp2->next;
head = temp; temp2->next = temp;
else }
{ }
Injibara University 51
o Adding a node to the left of a specific value in a singly linked list

void insert_left_y(int x, int y)


{ node *temp2 = head;
node *temp=new node; node *temp3;
temp->data=x; while(temp2->data!=y)
temp->next=NULL; {
if(head==NULL) temp3 = temp2;
head = temp; temp2 = temp2->next;
else }
{ temp->next = temp3->next;
temp3->next = temp;
}
}

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;

node *temp, *temp3; while(temp->data!=x)

if(head==NULL) {

cout<<"No data inside\n"; temp3 = temp;

if(head->data==x) temp = temp->next;

{ }

temp = head; temp3->next = temp->next;

head = head->next; delete temp;

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

 To create an empty list,


 create a head pointer
 set head pointer to NULL
Node *head;
head
head = NULL;
NULL
Or shortly,
Node *head = NULL;
 Head pointer initialized to NULL indicates an empty list
o Size of linked list
 To find the length of a list:
int length(ListNode *myList)
{
if (myList == NULL)
return 0;
else
return 1 + length(myList->next);
}
Double Linked lists

o Doubly Linked List is a variation of Linked list in which navigation is

possible in both ways either forward and backward easily as compared

to Single Linked List

o Each node points not only to Successor node (Next node), but also to

Predecessor node (Previous node).

o Advantage: given a node, it is easy to visit its predecessor (previous)

node. It is convenient to traverse linked lists Forwards and Backwards.

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 LinkedList - A LinkedList contains the connection link to the first Link


called First and to the last link called Last

o There are two NULL: at the first and last nodes in the linked list.

Injibara University 60
o Operations of Doubly Linked List

– Adding a node to the end of a doubly linked list

– Adding a node to the front of a doubly linked list

– Adding a node to the left of a specific data in a doubly linked list

– Adding a node to the right of a specific data in a doubly linked list

– Deleting a node from the end of a doubly linked list

– Deleting a node from the front of a 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

void insertFront(int x) else

{ {

node *temp = new node; temp->next = head;

temp->data = x; head->prev = temp;

temp->next = NULL; head = temp;

temp->prev = NULL; }

if(head == NULL) }

head = tail = temp;

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

element stored last will be retrieved first.

o It has a LIFO (Last In First Out) or FILO (First In Last Out) structure.

o Stack is a simple data structure, in which insertion and deletion occur at

the same end.

o Items can be inserted (“pushed”) and deleted (“popped”), but only the

most recently inserted element can be operated on.

o Stack is useful for temporary storage for dealing with nested structure;

expressions with in expressions, functions calling other functions,

directories with in directories.


Injibara University 73
o For example, we can place or remove a card or plate from top of the
stack only.

o Stacks are more restricted List with the following constraints:

– Elements are stored by order of insertion from "bottom" to "top“.

– Items are added to the top.

– 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.

o Peek(): returning the value of the top element in stack s

o isEmpty(): return true if and only if the stack is empty

o isfull(): return true if and only if the stack is full

o createStack(): make an empty stack (remove existing items from the


stack and initialize the stack to empty)

 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

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 Creating stack using linked list:
struct node
{
int data;
struct node* next;
struct node* prev;
};
node *head = NULL, *tail = NULL;

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

The figure above show insertion at the head of linked list


Injibara University 86
o Push an element to the top of the stack in a linked list
void insertEnd(int x)
{
node* temp = new node;
temp->data = x;
temp->next = NULL;
temp->prev = NULL;
if(head==NULL)
head = tail = temp;
else
{
tail->next = temp;
temp->prev = tail;
tail = temp;
}
} Injibara University 87
o Pop an element from the top of the stack using a linked list
void pop()
{
node *temp;
if(tail==NULL)
cout<<"No data inside\n";
else
{
temp = tail;
tail = tail->prev;
tail->next = NULL;
delete temp;
}
}
Injibara University 88
o Display the content of the top element in the stack using a linked
list
void displayTop()
{
node *temp;
if(tail==NULL)
cout<<"No data inside\n";
else
{
cout<<tail->data<<endl;
}
}

Injibara University 89
o Display the content of all elements in the stack in a forward manner in
a linked list

void displayForward() while(temp!=NULL)


{
{
node *temp;
cout<<temp-
if(head==NULL)
>data<<endl;
cout<<"No data inside\n";

else temp = temp->next;

{ }
temp = head; }

}
Injibara University 90
o Display the content of all elements in the stack in a backward manner in a
linked list

void displayBackward() while(temp!=NULL)

{ {

node *temp; cout<<temp->data<<endl;

if(tail==NULL) temp = temp->prev;

cout<<"No data inside\n"; }

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 This information is saved so that computer will know where to resume


execution in the calling function after the execution of the function has
been completed.

o This information is called activation record or stack frame.

o When a function is called arguments (including the return address) have to


be passed to the called function.

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

o Expression can be evaluated by machine by placing all operators before or after


their operands this method is called polish notation

– Example: 4 + 5 * 5

 simple calculator: 45

 scientific calculator: 29 (correct), but how?

– Computers solve arithmetic expressions by restructuring them from infix to


“post-fix notation” also called reverse-polish notation.

o The valuable aspect of RPN (Reverse Polish Notation or postfix )

– Parentheses are unnecessary

– Easy for a computer (compiler) to evaluate an arithmetic expression


Postfix (Reverse Polish Notation) 94
Injibara University
o There are three kinds of expressions:
– Infix notation:
• It is the normal (human-readable) way of expressing mathematical
expressions.
• Operators are written in between their operands. e.g. 4 + 5 * 5
– Prefix notation:
• Also called by its inventor as “Polish Notation”
• Operands are written before their operands. e.g. + 4 * 5 5
– Postfix notation:
• Operators are written after their operands
• Also called suffix notation or reverse polish notation (RPN).
e.g. 4 5 5 * +
Injibara University 95
Rules of Infix to Postfix conversion
o Rules:
– Operands immediately go directly to output. Operators are pushed into the
stack (including parenthesis, but not as output)
– Check to see if stack top operator is less than current operator
– If the top operator is less than, push the current operator onto stack
– If the top operator is greater than (or equal to) the current, pop top operator
and append on postfix notation, push current operator onto stack.
– If we encounter a right parenthesis, pop from stack until we get matching left
parenthesis.
o Precedence Priority of operators: High to low

– Priority 4: „(„ - only popped if a matching „)‟ is found.

– Priority 3: All unary operators (-, sin, cosin, ….)/exponents

– 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.

Move Current Stack -Grows towards Postfix(Output)


token left
1 A empty A
2 * * A
3 ( (* A
4 B (* AB
5 + +(* AB
6 C +(* ABC
7 ) * ABC+
8 * * ABC +*
9 D * ABC+*D
10 empty empty A B C + * D*

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 8 is pushed and the next item is the operator *:

Injibara University 100


o Next the operator + followed by 3:

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

Injibara University 101


6523+8*+3+*

Move Current Token Stack (grows toward left)


1 6 6
2 5 5 6
3 3 3 5 6

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

Injibara University 102


Excersise: Evaluate the expression 2 3 4 + * 5 * which was created by the
previous algorithm for infix to postfix.
Move Current Token Stack (grows toward left)
1 2 2
2 3 3 2
3 4 4 3 2
4 + 7 2
5 * 14
6 5 5 14
7 * 70
o Notes:
 Move 4: an operator is encountered, so 4 and 3 are popped, summed,
then pushed back onto stack.
 Move 5: operator * is current token, so 7 and 2 are popped,
multiplied, pushed back onto stack.
 Move 7: stack top holds correct value.
Injibara University 103
Chapter end!!!

???

Injibara University 104

You might also like