0% found this document useful (0 votes)
65 views72 pages

Data Structues Unit - I

Pdf

Uploaded by

Lalitha Abhigna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views72 pages

Data Structues Unit - I

Pdf

Uploaded by

Lalitha Abhigna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

JNTUH UNIVERSITY SYLLABUS COPY

CS302ES: DATA STRUCTURES

B.TECH II Year I Sem. L T P C


3 1 0 4
Prerequisites: A course on “Programming for Problem Solving”.

Course Objectives:
 Exploring basic data structures such as stacks and queues.
 Introduces a variety of data structures such as hash tables, search trees, tries, heaps, graphs.
 Introduces sorting and pattern matching algorithms

Course Outcomes:
 Ability to select the data structures that efficiently model the information in a problem.
 Ability to assess efficiency trade-offs among different data structure implementations or combinations.
 Implement and know the application of algorithms for sorting and pattern matching.
 Design programs using a variety of data structures, including hash tables, binary and general tree structures, search trees,
tries, heaps, graphs, and AVL-trees.

UNIT - I
Introduction to Data Structures, abstract data types, Linear list – singly linked list implementation, insertion, deletion and searching
operations on linear list, Stacks-Operations, array and linked representations of stacks, stack applications, Queues-operations, array and linked
representations.

UNIT - II
Dictionaries: linear list representation, skip list representation, operations - insertion, deletion and searching.
Hash Table Representation: hash functions, collision resolution-separate chaining, open addressing-linear probing, quadratic probing,
double hashing, and rehashing, extendible hashing.

UNIT - III
Search Trees: Binary Search Trees, Definition, Implementation, Operations- Searching, Insertion and Deletion, AVL Trees, Definition,
Height of an AVL Tree, Operations – Insertion, Deletion and Searching, Red –Black, Splay Trees.
II
UNIT - IV
Graphs: Graph Implementation Methods. Graph Traversal Methods.
Sorting: Heap Sort, External Sorting- Model for external sorting, Merge Sort.

UNIT - V
Pattern Matching and Tries: Pattern matching algorithms-Brute force, the Boyer –Moore algorithm, the Knuth-Morris-Pratt algorithm,
Standard Tries, Compressed Tries, and Suffix tries.

TEXTBOOKS:
1. Fundamentals of Data Structures in C, 2nd Edition, E. Horowitz, S. Sahni and Susan Anderson Freed, Universities Press.
2. Data Structures using C – A. S. Tanenbaum, Y. Langsam, and M.J. Augenstein, PHI/Pearson Education.

REFERENCE BOOKS:
1. Data Structures: A Pseudocode Approach with C, 2nd Edition, R. F. Gilberg and B.A. Forouzan, Cengage Learning.

III
LESSON PLAN

Week Unit Topics References Books

Week1 I abstract data types, Fundamentals of Data


Linear list – singly Structures in C, 2nd
linked list Edition, E. Horowitz, S.
Sahni and Susan
implementation,
Anderson Freed,
insertion, deletion Universities Press.
and searching
operations on linear
list, Stacks-
Operations, array and
linked representations
of stacks, stack
applications, Queues-
operations, array and
linked
representations.
Week 2 I abstract data types, Fundamentals of Data
Linear list – singly Structures in C, 2nd
linked list Edition, E. Horowitz, S.
Sahni and Susan
implementation,
Anderson Freed,
insertion, deletion Universities Press.
and searching
operations on linear
list, Stacks-
Operations, array and
linked representations
of stacks, stack
applications, Queues-
operations, array and
linked
representations.
Week 3 II Dictionaries: linear Data Structures: A
list representation, Pseudocode Approach
skip list with C, 2nd Edition, R. F.
Gilberg and B.A.
representation,
Forouzan, Cengage
operations - insertion, Learning.
deletion and
searching.
Hash Table
Representation:
hash functions,

1
collision resolution-
separate chaining,
open addressing-
linear probing,
quadratic probing,
double hashing, and
rehashing, extendible
hashing.
Week 4 II Dictionaries: linear Data Structures: A
list representation, Pseudocode Approach
skip list with C, 2nd Edition, R. F.
Gilberg and B.A.
representation,
Forouzan, Cengage
operations - insertion, Learning.
deletion and
searching.
Hash Table
Representation:
hash functions,
collision resolution-
separate chaining,
open addressing-
linear probing,
quadratic probing,
double hashing, and
rehashing, extendible
hashing.
Week 5 III Search Trees: Data Structures using C
Binary Search Trees, – A. S. Tanenbaum, Y.
Definition, Langsam, and M.J.
Augenstein,
Implementation,
PHI/Pearson Education
Operations-
Searching, Insertion
and Deletion, AVL
Trees, Definition,
Height of an AVL
Tree, Operations –
Insertion, Deletion
and Searching, Red –
Black, Splay Trees
Week 6 III Search Trees: Data Structures using C
Binary Search Trees, – A. S. Tanenbaum, Y.
Definition, Langsam, and M.J.
Augenstein,
Implementation,
Operations-

2
Searching, Insertion PHI/Pearson Education
and Deletion, AVL
Trees, Definition,
Height of an AVL
Tree, Operations –
Insertion, Deletion
and Searching, Red –
Black, Splay Trees
Week 7 IV Graphs: Graph Data Structures using C
Implementation Methods. – A. S. Tanenbaum, Y.
Graph Traversal Methods. Langsam, and M.J.
Sorting: Heap Sort, Augenstein,
External Sorting- Model PHI/Pearson Education
for external sorting,
Merge Sort.

Week 8 V Pattern Matching Data Structures using C


and Tries: Pattern – A. S. Tanenbaum, Y.
matching algorithms- Langsam, and M.J.
Augenstein,
Brute force, the
PHI/Pearson Education
Boyer –Moore
algorithm, the Knuth-
Morris-Pratt
algorithm, Standard
Tries, Compressed
Tries, and Suffix
tries.

3
UNIT – 1
INTRODUCTION
Software Development Life Cycle(SDLC)

Requirements


Analysis


Designing


Coding / Implementation


Debugging


Testing


Maintenance


Documentation

4
WHAT IS DATA?

The quantities, characters or symbols on which operations are


performed by a computer, which may be stored and transmitted
in the form of electrical signals and recorded on magnetic, optical
or mechanical recording media.

Example : c=a+b

WHEN DATA BECOMES INFORMATION?

Data : IHTAWS SI EMAN YM (collection of charecters)

Information : MY NAME IS SWATHI

If data is arranged in a systematic way then it gets a structure


and become meaningful.

❖ The meaningful or processed data is called information.

It is not difficult to understand that the data needs to be


managed in such a way so that it can produce some meaningful
information.

To provide an appropriate way to structure the data we need to


know about DATA STRUCTURES.

WHAT IS A DATA STRUCTURE?

A data structure is a systematic way to organize data so that it


can be used efficiently.

Ex: Arrays

5
Instead of creating multiple variables of same data type. Why not
create an array to store all the values.

Storing strings is equivalent of storing a sequence of characters.


This requires an array.

Examples:

1) Which data structure is used in implementing redo and undo


feature? Stack.

2) Which data structure is used to store an image as a bitmap?


Array.

3) Storing the friendship information on a social networking


site. Graph

WHAT IS A DATA TYPE?

Two important things about data types:

• Defines certain domain of values


• Defines operations allowed on those values

Ex.1: int type

✓ Takes only integer values


✓ Operations : addition, subtraction, multiplication, bitwise
operations etc.,

Ex.2: float type

✓ Takes only floating point values


✓ Operations : addition, subtraction, multiplication, division,
etc., (bitwise and % operations are not allowed).

6
USER DEFINED DATA TYPES:

In contrast to primitive data types, there is a concept of user


defined data types.

The operations and values of user defined data types are not
specified in the language itself but is specified by the user.

Ex: structure, union, and enumeration.

By using structures, we are defining our own type by combining


other data types.
struct point {
int x;
int y;
};
Abstract data types:

ADTs are like user defined data types which defines operations on
values using functions without specifying what is there inside the
function and how the operations are performed.

Example: Stack ADT

A Stack consists of elements of same type arranged in a


sequential order
Operations:
initialize() - initializing it to be empty
push() – insert an element into the stack
pop() – delete an element from the stack
isEmpty() – checks if stack is empty
isFull() – checks if stack is full

7
Think of ADT as a black box which hides the inner structure and
design of the data type from the user.

❖ There are multiple ways to implement an ADT

Example: A stack ADT can be implemented using arrays or linked


lists.

Why ADT?

❖ The program which uses data structure is called a


client program
❖ Client program has access to the ADT i.e., interface.
❖ The program which implements the data structure is
known as the implementation.

ADVANTAGE:

✓ Lets say, if someone wants to use the stack in the program,


then he can simply use push and pop operations without
knowing its implementation.

✓ Also, if in future, the implementation of stack is changed


from array to linked list, then the client program will work in
the same way without being affected.

❖ ADT provides abstraction.

From above we understood that, a stack ADT can be


implemented using arrays and linked list.

8
DEFINITION OF DATA STRUCTURE:

A Data structure is the organization of the data in


a way so that it can be used efficiently.
In other words, it is used to implement an ADT.

Ex.: In order to implement stack ADT we can use an array


data structure or linked list data structure.

**** ADT tells us what to be done


But Data structure tells us how to do it.

➔ ADT gives us blueprint.


➔ Data Structure gives us implementation.

Which Data Structure? (How to know which data structure to


use for a particular ADT?)

In reality, different implementations of ADT are compared for


time and space efficiency. The one best suited according to the
current requirement of the user will be selected.

Ex.: stack ADT

Arrays linked list


(used for time efficiency) (used for space efficiency)

9
Advantages of Data Structures:

1) Efficiency – proper choice of data structure make program


efficient in terms of space and time.
2) Reusability – one implementation can be used by multiple
client programs.
3) Abstraction – data structure is specified by an ADT which
provides a level of abstraction. This client program doesn’t
have to worry about the implementation details.

Types of data structures:

Data structures

Linear data structure non-linear data structure

1)Linear data structure :

A data structure is linear, when all the elements are


arranged in a linear(squential) order.

Ex.: Arrays
Queues
Stack
Linked list.

2)Non-linear data structure :

A data structure is non linear, when all the elements


are not arranged in a linear(sequential) order. There is
no linear arrangement of the elements.

10
Ex.: Tree’s , Graph’s.

3)Static data structure :

In this, the memory is allocated at run time. Therefore,


maximum size is fixed.
Advantage : fast access
Disadvantage : slower insertion and deletion.
Ex.: Array.

4)Dynamic data structure :

In this, the memory is allocated at run time. Therefore,


maximum size is flexible.
Advantage : fast insertion and deletion.
Disadvantage : slower access.
Ex.: linked lists.

Definition of Data Structure:

A data structure is the organization of the data in a way


(memory location) so that it can be used efficiently.

In order to use data efficiently, we have to store it


efficiently.

Efficiency of data structures is always measured in terms of


time and space.

An ideal data structure could be the one that takes the least
possible time for all its operations and consumes the less memory
space.

11
Non-primitive data structure
Linear non-linear
(sequential) (random)
1. Arrays 1. Trees
2. Lists i. binary
i. Singly LL ii. BST
ii. Doubly LL 2. Graphs
iii. Circular LL
3. Stacks
4. Queues

Common operations to be performed on DS’s :


1) Searching
2) Sorting
3) Insertion
4) Deletion
5) Updation

Linear data structure :

In linear data structure, all the elements are


organized in a sequential order.

Ex. : Arrays, lists, stacks, queues.

Arrays :

Array is a collection of similar data elements under


same name.

Elements in memory are organized in sequential order.

12
Operations to be performed onto arrays
1) Insertion
2) Deletion
3) Searching
a. Linear search
b. Binary search
4) Sorting
a. Bubble sort
b. Quick sort
c. Merge sort ., etc.,
Advantages :

1) Similar data elements.


2) Random Access (index is known)
3) Suitable when the number of elements are alredy
known.
4) Implementation of stacks and queues.

Disadvantages :

1) Static memory allocation


-- during compile time – specify size of array.

Ex. : declare array A[10]


• Not possible to increase the size
Ex. : declare array A[100]
• If we use only 10 elements memory then 90
elements space will be wasted.

13
2) Insertion and deletion

Ex. : a[0] a[1] a[2] a[3] a[4] a[5]


10 20 30 40 50
Insert 5; 5 10 20 30 40 50
Delete 10; 5 20 30 40 50

LINKED LIST :

The elements can be stored randomly in memory locations,


but there will be a link between one element to another element.
So, element is represented as a node.

Element -----→ node


10 two fields
20 →data – insert value
30 →address/pointer/next
… --represents address of next node
--link of next element

Representation of node :

data next

Value address of next element

14
If it contains 3 nodes
Head Tail

10 2000 20 3000 30 NULL

1000 2000 3000

--last element address field indicates end of list


--LL have head(starting element) and tail(end element).

➔ Before going to program first we have to create node with


the help of structure . because structure is a user defined
data type which adopts multiple dissimilar data elements.

declaration of node:

struct node
{
int data;
struct node *next;
}*new;

◼ After creating node, we have to allocate memory


dynamically.
New=(struct node *)malloc(sizeof(struct node));

struct node *head;(points first element)


struct node *tail;(points last element)
struct node *temp;(to display)

15
Create a list

Assume; data -- 10, 20, 30


Address -- 1000, 2000, 3000

I iteration:- data -- 10(new)

10 NULL

Head,tail

II iteration :- data -- 10, 20(new)

10 2000 20 NULL

Head tail

**** to insert next element


1. We have to establish the link first .
tail →next = new;
2. Assign next element which we want to insert.
tail=new;

III iteration :- data -- 10, 20, 30(new)

10 2000 20 3000 30 NULL

Head tail

16
→Sample code to create list :-
do
{ new=(struct node *)malloc(sizeof(struct node));
scanf(“%d”,&value);
new→data=value;
new→next=NULL;
if(head==NULL)
{
head=new;
tail=new;
}
else
{
tail→next=new;
tail=new; }
printf(“Y-continue N-exit”);
fflush()stdin;
scanf(“%c”,&ch);
}while(ch==’Y’);
Trace:::: data – 20, 30, 50
Address – 2000, 3000, 5000.

I) Value=20(new) 20 NULL (Head,tail)

II) value=30(new) 20 3000 30 NULL

Head tail
III) value=50(new)

20 3000 30 5000 50 NULL


Head tail

17
Display the list:

20 3000 30 5000 50 NULL

Head tail

→For display, we have to move every node to empty node.


struct node *temp;

→sample code for display:

temp=head;
while(temp!=NULL)
{
printf(“%d”,temp→data);
temp=temp→next;
}

18
INSERTION OF ELEMENT IN THE EXISTING LINKED LIST

1) Insertion of the element at the beginning of the list.


2) Insertion of the element at the end of the list.
3) Insertion of the element at specified location.

➔ To perform insertion operation, first we need to perform two


steps
1. We have to allocate memory dynamically
2. Then, we have to read the value.

1) INSERTION OF THE ELEMENT AT THE BEGINNING OF


THE LIST.

10 2000 20 3000 30 NULL

Head tail

→Sample code

scanf(“%d”,&value); //5
new→data=value;
new→next=head;
head=new;

5 1000 30 NULL
10 2000 20 3000

Head tail

19
2) INSERTION OF THE ELEMENT AT THE END OF THE
LIST.

5 1000 30 NULL
10 2000 20 3000

Head tail

1. We have to allocate the memory dynamically.


2. Read new node.
3. Then assign link between them.

→sample code

scanf(“%d”,value); //35 (address=3500)


new→data=value;
tail→next=new;
new→next=NULL;
tail=new;

5 1000 30 3500 35 NULL


10 2000 20 3000

Head tail

20
3) INSERTION OF THE ELEMENT AT SPECIFIED
LOCATION.

5 1000 30 NULL
10 2000 20 3000

Head tail

1. We have to allocate memory dynamically.


2. Read new node (value=15,address=1500)
3. If we want to insert at position 2 i.e., between values 10 and
20
a. Then we have to reach position 1 i.e., node with value
10.

(index of the list starts from 0 as if array)

Sample code

Scanf(“%d”,&value);
Scanf(“%d”,&pos);
temp=head;
for(i=0;i<pos-1;i++)
{ temp=temp→next; }
new→data=value;
new→next=temp→next;
temp→next=new;

5 1000 30 NULL
15 2000 20 3000
10 1500

Head tail

21
DELETION OF AN ELEMENT FROM THE EXISTING LINKED
LIST:

In LL, if we want to delete an element

1) Disconnect the link


2) Connect the remaining elements→ such that they are again
linked

5 1000 30 NULL
15 2000 20 3000
10 1500

Head tail

I).DELETE ELEMENT AT BEGINNING

15 2000 20 3000 30 NULL


10 1500

Head tail

Sample code:

temp=head;
head=head→next;
temp→next=NULL;

1. we consider ‘temp’ variable and assign head to temp.


(temp=head)
2. now, since we are deleting first element. we have to shift
‘head’ to ‘next’ element.(head=head→next)

22
3. now, we are disconnecting this ‘temp’ variable by removing
the link. (temp→next=NULL)

II. DELETE THE ELEMENT AT THE END

5 1000 20 3000
10 1500 15 2000

Head tail

Sample code:

temp=head;
while(temp→next!=tail)
{
temp=temp→next;
}
temp→next=NULL;
tail=temp;

23
III. DELETE ELEMENT AT SPECIFIED POSITION:

5 1000 30 NULL
15 2000 20 3000
10 1500

Head tail
Index 0 1 2 3 4

Sample code:

scanf(“%d”,&pos);
temp=head;
for(i=0;i<pos-1;i++)
{
temp=temp→next;
}
temp→next=temp→next→next;

5 1000 30 NULL
10 2000 20 3000

Head tail
Index 0 1 2 3 4

24
COUNTING NUMBER OF NODES IN THE LINKED LIST

5 1000 30 NULL
15 2000 20 3000
10 1500

Head tail

Sample code

int count=0;
temp=head;
while(temp!=NULL)
{
count++;
temp=temp→next;
}
printf(“count=%d”,count);

25
ADVANTAGES OF LINKED LIST

1. no wastage of memory
2. no need to use contiguous memory locations
3. insertion and deletion becomes simple
4. linear data structure like stack , queue can be implemented
using LL
5. can store any type of data in node

DISADVANTAGES OF LINKED LIST

1. random accessing is not possible


2. only forward traversal is possible.
3. binary search algorithm is not possible
4. reversing linked list is complex – as it is singly LL
5. extra pointer is required to store the address of next node

26
CIRCULAR LINKED LIST :

In circular linked list; the address field of last


node contains the address of head.

Assume; data -- 10, 20, 30


Address -- 1000, 2000, 3000

Singly linked list .,

10 2000 20 3000 30 NULL

Head tail

Circular linked list.,

10 2000 20 3000 30 1000

Head tail

➔ Create a node sing structure:

struct node
{
int data;
struct node *next;
}*new,*head,*tail,*temp;

→allocate the memory dynamically


new=(struct node *)malloc(sizeof(struct node));

27
→create a circular linked list

scanf(“%d”,&value);
new→data=value; new node
new→next=NULL;
30 NULL
if(head==NULL)
{
head=new;
tail=new;
}
else
{
tail→next=new;
tail=new;
tail→next=head;
}
printf(“’y’ continue ‘n’ exit”);
fflush(stdin);
scan(“%c”,&ch);
}while(ch==’y’);

Trace:

I.
10 NULL

1000 (new node)/head/tail


II.

10 2000 20 1000

Head tail

28
III.

10 2000 20 3000 30 1000

Head tail

//Display the Circular Linked List

Sample code:

temp=head;
while(temp→next!=NULL)
{
printf(“%d”,temp→data);
temp=temp→next;
}
printf(“%d”,temp→data);

//output : 10 20 30

29
INSERTION

3 cases→ 1) insertion at the beginning of the list


2) insertion at the end of the list
3) insertion at the specified location

1) insertion at the beginning of the list:

existing LL::

10 2000 20 3000 30 1000

Head tail

Output::

5 1000 10 2000 20 3000 30 500

Head tail

Sample code:

new=(struct node *)malloc(sizeof(struct node));


scanf(“%d”,&value);
new→data=value;
new→next=head;
tail→next=new;
head=new;

30
2) insertion at the end of the list:
existing LL::

10 2000 20 3000 30 1000

Head tail
Output::

10 2000 20 3000 30 4000 40 1000

Head tail

Sample code:

new=(struct node *)malloc(sizeof(struct node));


scanf(“%d”,&value);
new→data=value;
tail→next=new;
new→next=head;
tail=new;

31
3) Insertion at the specified location of the list

existing LL::

10 2000 20 3000 30 1000

Index 0 1 2
Head tail

Output::

10 2000 20 2500 25 3000 30 1000

Head tail

Sample code:

scanf(“%d”,&pos); //2
new=(struct node *)malloc(sizeof(struct node));
scanf(“%d”,&value);
new→data=value;
temp=head;
for(i=0;i<pos-1;i++)
{
temp=temp→next;
}
new→next=temp→next;
temp→next=new;

32
DELETION:

3 cases: 1) deletion at beginning of the list


2) deletion at the end of the list
3) deletion at the specified location

1) Deletion at the beginning of the list:

Existing LL

10 2000 20 2500 25 3000 30 1000

Head tail

Output

20 2500 25 3000 30 2000

Head tail

Sample code:

temp=head;
head=head→next;
tail→next=head;
temp→next=NULL;

33
2) Deletion at the end of the LL:

Existing LL

10 2000 20 2500 25 3000 30 1000

Head tail

Output

10 2000 20 2500 25 1000

Head tail

Sample code:

temp=head;
while(temp→next!=tail)
{ temp=temp→next; }
tail→next=NULL;
temp→next=head;
tail=temp;

34
3) Deletion of the element at the specified location:

Existing LL

10 2000 20 2500 25 3000 30 1000

Index 0 1 2 3
Head tail

Output

10 2000 20 2500 30 1000

Head tail

Sample code:

scanf(“%d”,&pos);
temp=head;
for(i=0;i<pos-1;i++)
{
temp=temp→next;
}
temp→next=temp→next→next;

35
DOUBLY LINKED LIST:

In this we have to establish two links for every node.


→every node will have two address fields i.e., every
node will link two different nodes
1) Next node(address next node)
2) Previous node(address of previous node)

Representation of node

Previous data next

Address field address field

Store address stores address of


Of prev. node next node

If it is head, if it is tail,
Then ., prev=NULL then ., next=NULL

Ex:-
1000 20 3000 2000 30 NULL
NULL 10 2000

1000 2000 3000


Head tail

36
Create node using structure:

struct node
{
struct node *prev;
int data;
struct node *next;
}*new,*head,*tail,*temp;

Create a list:

do
{
new=(struct node *)malloc(sizeof(struct node));
scanf(“%d”,&value);
new→prev=NULL;
new→data=value;
new→next=NULL;

if(head==NULL)
{
head=tail=new;
}
else
{
tail→next=new;
new→prev=tail;
tail=new;
}
Printf(“’y’ continue ‘n’ exit”);
}while(ch==’y’);

37
Trace:

I) NULL 10 2000
1000(new,head,tail)

II) 1000 20 NULL


NULL 10 2000

Head tail

III)
1000 20 3000 2000 30 NULL
NULL 10 2000

1000 2000 3000


Head tail

Display elements of list:

temp=head;
while(temp!=NULL)
{
printf(“%d”,temp→data);
temp=temp→next;
}

// 10 20 30

38
INSERTION

1) Insertion at the beginning:

Existing LL.,

1000 20 3000 2000 30 NULL


NULL 10 2000

1000 2000 3000


Head tail

Output.,

500 10 2000 2000 30 NULL


NULL 5 1000 1000 20 3000

500 1000 2000 3000


Head tail

Sample code:

new=(struct node *)malloc(sizeof(struct node));


scanf(“%d”,&value);
new→prev=NULL;
new→data=value;
new→next=head;
head→prev=new;
head=new;

39
2) Insertion at the end of the list:

Existing LL.,

1000 20 3000 2000 30 NULL


NULL 10 2000

1000 2000 3000


Head tail

Output.,

1000 20 3000 3000 40 NULL


NULL 10 2000 2000 30 4000

1000 2000 3000 4000


Head tail

Sample code:

new=(struct node *)malloc(sizeof(struct node));


scanf(“%d”,&value);
new→prev=tail;
new→data=value;
new→next=NULL;
tail→next=new;
tail=new;

40
3) Insertion at the specified location of the list:

Existing LL.,

1000 20 3000 2000 30 NULL


NULL 10 2000

1000 2000 3000


Index 0 1 2
Head tail

Output.,

1000 20 2500 2500 30 NULL


NULL 10 2000 2000 25 3000

1000 2000 2500 3000


Head tail

Sample code:

new=(struct node *)malloc(sizeof(struct node));


scanf(“%d”,&value);
scanf(“%d”,&pos);
temp=head;
for(i=0;i<pos-1;i++)
temp=temp→next;
new→prev=temp;
new→data=value;
new→next=temp→next;
temp→next→prev=new;
temp→next=new;

41
DELETION

1) Deletion at the beginning of the list:

Existing LL:

1000 20 2500 2500 30 NULL


NULL 10 2000 2000 25 3000

1000 2000 2500 3000


Head tail
NULL 10 NULL
Output:
1000 (temp)

2000 25 3000 2500 30 NULL


NULL 20 2500

2000 2500 3000


Head tail

temp=head;
head=head→next;
temp→next=NULL;
head→prev=NULL;

42
2) Deletion at the end of the list:

Existing LL:

1000 20 2500 2500 30 NULL


NULL 10 2000 2000 25 3000

1000 2000 2500 3000


Head tail
NULL 30 NULL
Output:
3000

1000 20 2500 2000 25 NULL


NULL 10 2000

1000 2000 2500


Head tail

temp=tail;
tail=tail→prev;
temp→prev=NULL;
tail→next=NULL;

43
3) Deletion at the specified location:

Existing LL:

1000 20 2500 2500 30 NULL


NULL 10 2000 2000 25 3000

1000 2000 2500 3000


Head tail
NULL 25 NULL
Output:
2500

1000 20 3000 2000 30 NULL


NULL 10 2000

1000 2000 3000


Head tail

scanf(“%d”,&pos);
temp=head;
for(i=0;i<pos-1;i++)
temp=temp→next;
temp→next=temp→next→next;
temp→next→prev=temp;

44
STACKs

- Stack is a linear data structure.


- elements are arranged in sequential manner
- it follows Last In First Out(LIFO) mechanism
- example : 1) arranging plates in a tray
2) arranging coins or books
3) arranging CDs in CD stand
- two basic operations.,
1) PUSH – inserting elements into stack
2) POP – deleting elements from stack
These operations can be performed only on top side., i.e.,
TOP(top of the stack).

PUSH POP

TOP=-1

STACK(empty)

45
If we inserted 1 element into stack say 10. Then top=1.,i.e.,top
will be incremented by one.

PUSH

TOP=1 10

STACK

PUSH

TOP=2 20

10

STACK

46
PUSH

TOP=3 30

20

10

STACK

If we deleted an element from stack, then top=2 i.e., top will


decrement its value by one.

POP

TOP=2 20

10

STACK

47
➔ If we want to PUSH(insert) elements, then we have to
increment TOP first then insert element into stack.
➔ If we want to POP(delete) element, then we have to
decrement TOP first then delete element.

Before implementing stacks we need to understand two


conditions.,

1) OVERFLOW CONDITION:

when stack is already full and still we are trying to insert


element into stack then in this situation stack overflow
occurs.

PUSH TOP=6 60

50

40

30

20

10

STACK(full)

48
2)UNDERFLOW CONDITION:

When the stack is empty and still we want to delete element


then in this situation stack underflow occurs.

POP

STACK(empty)
TOP=-1

49
Implementation of stacks using arrays

Since, we are using arrays we have to give size of the array


before itself as it is static memory allocation.

/* SIZE=10
TOP=-1
STACK[10] */

PUSH() → To insert the elements into stack


(increments’s TOP by 1)

push()
{
scanf(“%d”,&ele);
if(TOP==SIZE-1)
{
printf(“overflow”);
}
else
{
TOP++;
STACK[TOP]=ele;
}
}

50
POP() → To delete the element from the stack
(decrement’s TOP by 1)

pop()
{
if(TOP==-1)
printf(“underflow”);
else
{
ele=STACK[TOP];
TOP--;
}
}

DISPLAY() → To display the elements of the stack

display()
{
if(TOP!=-1)
{
for(i=TOP;i>=0;i++)
{
printf(“%d”,STACK[i]);
}
}
else
printf(“empty stack”);
}

Disadvantage of array representation is., we have to give


array size before itself and if we want to increase the size
we cannot do it as it is static memory allocation.

51
Implementation of stack using linked list:

PUSH POP

TOP=-1

Stack implementation using Linked List

Declaration of node using structures

struct node
{
int data;
struct node *next;
}*new,*temp,*top;

52
INSERTION of ELEMENT into STACK

push()
{
new=(struct *node)malloc(sizeof(struct node));
scanf(“%d”,&ele);
if(top==NULL)
{
new→data=ele;
new→next=NULL;
top=new;
}
else
{
new→data=ele;
new→next=top;
top=new;
}
}

TOP

30 2000 20 1000 10 NULL

53
DELETION of ELEMENT from the STACK

pop()
{
If(top==NULL)
Printf(“stack is empty”);
Else
{
Temp=top;
Printf(“%d is deleted ”,top→data);
Top=top→next;
Temp→next=NULL;
Free(temp);
}
}

54
Applications of Stack:

• Conversion of infix expression to postfix expression


• Evaluation of a postfix expression
• Conversion of infix expression to prefix expression
• Balancing the parenthesis/ symbols

NOTE:
+,-,*,/ … Operators

A,B,C … are Operands

INFIX EXPRESSION
<operand>operator<operand>
Ex: A+B

POSTFIX EXPRESSION
<operand1><operand2>operataor
EX: AB+

PREFIX EXPRESSION
Operator<operand1><operand2>
EX: +AB

55
1) CONVERSION OF INFIX TO POSTFIX EXPRESSION

INPUT - infix expression(we consider it as string and read


each character one by one to convert it into postfix
expression)

STEPS REQUIRED FOR CONVERSION(algorithm)

1. If the character is LEFT PARENTHESIS, simply push to the


stack.
2. If the character is OPERAND, simply ADD to the POSTFIX
EXPRESSION.
3. If the character is an OPERATOR, check whether stack is
empty.
a. If the stack is empty, then push operator into stack.
b. If the stack is not empty, then check the priority of the
operator.
i. If the priority of the operator is greater than the
operator present at stack then push the operator into
stack.
ii. if the priority of an operator is less than or equal to
operator present at top of the stack then pop the
operator from stack and add to POSTFIX EXPRESSION
and goto step (i).
4. If the character is RIGHT PARENTHESIS, then pop all the
operators from the stack until it reaches LEFT PARENTHESIS
and add to POSTFIX EXPRESSION.
5. After reading all characters ,still if stack is not empty then pop
and add to postfix expression .

Note : we push only operators in to stack not operands.

56
Ex: INFIX EXPRESSION → A+B*C

+ ABC *+
POSTFIX EXPRESSION
STACK

2)EVALUATING OF POSTFIX EXPRESSION

• Only one stack is used


• We push only operands into stack so it is operand
stack.

STEPS:
1) If the character is an operand, then simply PUSH into the
stack
2) If the character is an operator, POP top two operands from
the stack, perform calculation and PUSH the result back into
stack.
3) After reading all the characters from the POSTFIX EXPRESSION
stack will be having only the value which is the result.

57
EX: POSTFIX EXPRESSION → 562*+

Character stack
5

58
* 6 * 2 = 12

12

+ 5 + 12 = 17

17

EX2: 4 6 7 2 + - *
EX3: 5 4 6 + * 4 9 3 / + *

3)Balancing symbols

(
[ expressions
{ → block & statements

1 way is counting open symbols and counting closed


symbols

Drawback is [(a+b)] → 2 open and 2 closed one then valid


But if expression is [(a+b]) → 2 open n 2 closed valid
but still not balanced .

59
So, in order to overcome the above mentioned drawback we
implement it using stacks.

Steps:
1) Read character from expression.
2) If character is open symbol (,[,{ → push symbol into stack
3) If character is closed symbol ),],} →
a. Check if stack is empty , if TRUE expression is
unbalanced
b. If stack is not empty, pop the symbol from stack with the
symbol which is read. If doesn’t matches expression is
unbalanced else repeat the process
4) After reading all characters of expression still stack is not
empty → unbalanced.

EX: [(a+b)(a-b)]

Conversion of infix to postfix expression → operator stack


Evaluation of postfix expression → operand stack
Balancing symbols → symbol stack

60
QUEUE

• Linear data structure


• Elements are in sequential manner
• Follows the First In First Out(FIFO) mechanism
• Ex.: standing on a line for ticket reservation
• Two basic operations →
1) Enqueue – insertion of element into queue
2) Dequeue – deletion of element from queue
• Two conditions →
1) OVERFLOW – insertion of element into full queue
2) UNDERFLOW – deletion of element from empty queue

• Two ends
1) FRONT – points to starting element
2) REAR – points to ending element

• Representation

QUEUE

Front Rear
(DEQUEUE) (ENQUEUE)

Initially front = rear = -1


ENQUEUE is done at rear, DEQUEUE is done at front.
For every enqueue, rear is incremented by 1.
For every dequeue, front is incremented by 1.

61
IMPLEMENTATION OF QUEUE USING ARRAYS

QUEUE[];
SIZE = 10
FRONT = REAR = -1

ENQUEUE()
{
If(rear==size-1)
printf(“overflow”);
Else
{
scanf(“%d”,&ele);
If(front==-1)
front=0;
rear++;
Queue[rear]=ele;
}
}

QUEUE

Front=Rear=-1

QUEUE
10

Front,Rear

62
QUEUE
10 20

Front Rear

QUEUE
10 20 30

Front Rear

QUEUE
10 20 30 40

Front Rear

63
DEQUEUE()
{
If(rear==-1||front>rear)
{
Printf(“underflow”);
}
Else
{
Ele=queue[front];
Printf(“%d is deleted”,ele) ;
Front++;
}
}

INITIALLY.,
QUEUE
10 20 30 40

Front Rear

QUEUE
20 30 40

Front Rear
QUEUE
30 40

Front Rear

64
QUEUE
40

Front,Rear

QUEUE

Rear Front

DISPLAY()
{
If(rear==-1||front>rear)
Printf(“empty queue”);
Else
{
For(i=front;i<=rear;i++)
{
Printf(“%d”,queue[i]);
}
}
}
QUEUE
10 20 30 40

Front Rear

65
QUEUE IMPLEMENTATION USING LINKED LIST

struct node
{
int data;
struct node *next;
}*new,*front,*rear,*temp;

//initially
Front=rear=NULL(-1);

ENQUEUE() // insertion done at rear end → rear++


{
new=(struct *node)malloc(sizeof(struct node));
scanf(“%d”,&ele);
new→data=ele;
new→next=NULL;
if(rear==NULL)
front=rear=new;
else
{
rear→next=new;
rear=new;
}
}

66
Initially , no node(no element) → front=rear=NULL

new
10 NULL

1000
Front,rear

new

20 NULL
10 2000

1000 2000
Front rear

new

20 3000 30 NULL
10 2000

1000 2000 3000


Front rear

new

20 3000 30 4000 40 NULL


10 2000

1000 2000 3000 4000


Front rear

67
Dequeue() // deletion done at front end ➔ front++
{
If(front==NULL)
printf(“queue is empty”);
else
{
Temp=front;
Front=front→next;
Temp→next=NULL;
Free(temp);
}
}

20 3000 30 4000 40 NULL


10 2000

1000 2000 3000 4000


front rear

20 3000 30 4000 40 NULL


10 NULL

1000 2000 3000 4000


temp front rear

➔ element 10 is deleted from queue and elements available in


queue are 20, 30, 40.

68
Display()
{
Temp=front;
If(front==NULL)
{
Printf(“queue is empty”);
}
Else
{
While(temp!=NULL)
{
Printf(“%d”,temp→data);
Temp=temp→next;
}
}
}

Output: 10 20 30 40

69
UNIT -2
DICTIONARIES:
Dictionary is a collection of pairs of key and value where every value is associated with the
corresponding key.
Basic operations that can be performed on dictionary are:
1. Insertion of value in the dictionary
2. Deletion of particular value from dictionary
3. Searching of a specific value with the help of key

Linear List Representation


The dictionary can be represented as a linear list. The linear list is a collection of pair and value.
There are two method of representing linear list.
1. Sorted Array- An array data structure is used to implement the dictionary.
2. Sorted Chain- A linked list data structure is used to implement the dictionary

Structure of linear list for dictionary:

class dictionary
{
private:
int k,data;
struct node
{
public: int key;
int value;
struct node *next;
} *head;

public: dictionary();
void insert_d( );
void delete_d( );
void display_d( );
void length();
};
Insertion of new node in the dictionary:
Consider that initially dictionary is empty then
head = NULL
We will create a new node with some key and value contained in it.

70

You might also like