0% found this document useful (0 votes)
10 views20 pages

Ds 1

Question paper

Uploaded by

tchate45
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)
10 views20 pages

Ds 1

Question paper

Uploaded by

tchate45
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/ 20

CSPCC2002: Data Structures

Unit 1

Introduction To Data Structure, Stack Queues


- Data structure - linear and nonlinear,
- abstract data type Algorithm,
- The stack as an ADT,
- stack applications –
- Basic Definition and examples: Infix, Postfix, and Prefix,
- Program to evaluate a Postfix expression,
- Limitations of the program,
- The queue and its sequential representation,
- The queue as an ADT.

- Data structure - linear and nonlinear,

❖ Data Structure:
Definition:
● Data is a collection of numbers, alphabets and special symbols which are used to represent an
information.
● The proper arrangement of data is known as data structure.
● The systematic representation of data in main memory is known as data structure.
● Data can be organized in different ways.
● The logical or mathematical model of a particular organization of data is called as data structure.
● A data structure is a way of storing data in a computer so that it can be used efficiently.

Need of Data Structure:

● Data structures are an important way of organizing information or data in a computer.


● It has a different ways of storing & organizing data in a computer.
● It helps to understand relationship of one data element with other.
● It helps to store data in logical manner.
● We need to store the data in such a way that may grow & shrink dynamically.
● If we organize the information in some proper manner then we can access it using efficient
algorithm.
● Data structures are uses many efficient algorithms, & because of that it is possible to manage the
huge amounts of data.
- Classification of data structure:
The classification of data structure mainly consists of :
1. Primitive data structure
2. Non-primitive data structure

Primitive data structure :


● The primitive data structures are known as basic data structures.
● All basic data types of any language are called as primitive data types.
● It defines how the data will be internally represented in, stored and retrieve from memory.
● Example.
1. Integer
2. Float
3. Character
4. Pointer

Non-Primitive data structure :


● All the data structures derived from primitive data structures are called as non-primitive data
structures.
● The non-primitive data structures are highly developed complex data structures.
● The non-primitive data structure is responsible for organizing the group of homogeneous and
heterogeneous data elements.
● Example.
1. Arrays
2. Lists
I) Linear data structure
a) Stack
b) Queue
II) Non-Linear data structure
a) Tree
b) Graph
3. Files
Linear and Non Linear Data Structure:

● Data structures are basically a way of storing and logically implementing the data elements.
● Primitive data structures which include the int, char, float, double and the non-primitive data
structures can broadly be classified into two types:

1. Linear Data Structure


2. Non-Linear Data Structure

Linear Data Structure:

● In this type of data structure, all the data elements are stored in a particular sequence.
● All elements are arranged in linear fashion.
● The sequential organization of data elements is known as linear data structure.
● Examples: Array, Linked List, Stack, Queue, etc.

Non-Linear Data Structure:

● In this type of data structure, all the data elements do not form any sequence.
● All elements are arranged in non-linear fashion.
● The randomly organization of data elements is known as non-linear data structure.
● Examples: Tree, Graph, Table, etc.

❖ Operations on Data Structure:

The basic operations that are performed on data structures are as follows:
1. Insertion:
It is adding a new data in data structure.
2. Deletion:
It is removing a data from existing data structure
3. Searching:
It is finding location of data within given data structure
4. Sorting:
It is an arranging data in some logical order, it may be in ascending or descending order.
5. Traversing:
It is an operation that access each and every element.
6. Merging:
It is used to combine the data items of two data structure into single data structure.
- Abstract data type Algorithm,
•A useful tool for specifying the logical properties of a data type is the
abstract data type, or ADT. Fundamentally, a data type is collection of values and a set of
operations on those values.
That collection and those operations form a mathematical construct
that may be implemented using a particular hardware or software
data structure.
The term "abstract data type" refers to the basic mathematical
concept that defines the data type.

● ADT stands for Abstract Data Types.


● Abstract Data type (ADT) is a type for objects whose behavior is defined by a set of value and a
set of operations.
● The definition of ADT mentions what operations are to be performed on the objects without
giving the detail information about the how these operations will be implemented.
● It does not specify how data will be organized in memory and what algorithms will be used for
implementing the operations.
● It is called as “Abstract” because it will show only essential details and hide the unwanted details.
● The process of providing only the essentials details and hiding the unwanted details is known as
abstraction.
● For example, we use int, float, char data types for storing values and performing the various
operations. But we don’t know how these operations are performed on the data.
● It means user only understand what are the data types and what it does but they don’t know how it
will manage data in memory and how it will do the various operations.
● ADT as a black box which hides the inner structure and design of the data type.

• To illustrate the concept of an ADT and our specification method,


consider the ADT RATIONAL, which corresponds to the mathematical
concept of a rational number.
•A rational number is a number that can be expressed as the quotient
of two integers.
• The operations on rational numbers that we define are the creation
of a rational number from two integers, addition, multiplication, and testing for equality.
- The stack as an ADT
 A stack is an ordered collection of items nto which new items may be
inserted and from which items may be deleted at one end, called thetop of the stack.
 a stack is an abstract data type that serves as a collection of elements with two main
operations: Push, which adds an element to the collection, and. Pop, which removes the most
recently added element.
 The representation of a stack as abstract data type is straightforward.
We use eltype to denote the type of the stack element and parameterize the stack type with
eltype.

Stack is a linear data structure in which the operations are performed based on LIFO or FILO
principle.
A Collection of similar data items in which both insertion and deletion operations are performed
based on LIFO or FILO principle.
In a stack, adding and removing of elements is performed at single position which is known as
"Top".
That means, new element is added at the top of the stack and an element is removed from the
top of the stack.
In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out
and First In Last Out) manner.
Below diagram shows the behavior of a stack:
 In a stack, the insertion operation is performed using a function called "push" and deletion
operation is performed using a function called "pop".
 In the above figure, PUSH and POP operations are performed at top position in the stack. That
means, both the insertion and deletion operations are performed at one end (i.e at Top).

Example:
If we want to create a stack by inserting 10,45,12,16,35 and 50. Then 10 becomes the bottom
most element and 50 is the top most element. Top is at 50 as shown in the image below:

Operations on a Stack: The following operations are performed on the stack.


1. Initialize – To initialize the stack, in this operation -1 value set to Top variable.
2. Empty – To check whether stack is empty or not.
3. Full – To check whether the stack is full or not.
4. Push – To insert the element onto the stack is known as Push operation.
5. Pop – To delete the element from the stack is known as Pop operation.
6. Print – To display all elements of the stack.

- stack applications
Applications of STACK:
1. Expression Evaluation.
2. Expression Conversion.

a) Infix to Postfix
b) Infix to Prefix
c) Postfix to Infix
d) Prefix to Infix

3. Simulation of recursion.
4. Function call.
5. Reversing the list.
6. Parsing.
- Basic Definition and examples: Infix, Postfix, and Prefix,

• This section examines it application that illustrates the different types


of stacks and the various operations and functions defined upon
them

What is an Expression?
Expression is a collection of operands and operators.
Operator is a symbol which indicate operation to be perform like arithmetic operation or
logical operation or conditional operation etc.
Operands are the values on which operation to be perform.

Expression Types:
1. Infix Expression
2. Postfix Expression
3. Prefix Expression

1. Infix Expression: In infix expression, operator is used in between operands.


Syntax:

Example:
2. Postfix Expression: In postfix expression, operator is used after operands.
Syntax:

Example:

3. Prefix Expression: In prefix expression, operator is used before operands.


Syntax:

Example:

Any expression can be represented using the above three different types of expressions. And we can
convert an expression from one form to another form like Infix to Postfix, Infix to Prefix and vice versa.

•Worse still is attempting to solve a problem with an incorrect


program, only to have the program produce incorrect results without
the slightest trace of an error message.
•In these cases the programmer has no indication that the results are
wrong and may therefore make faulty judgments based on those
results.
•A major criticism of this program is that it does nothing in terms of
error detection and recovery.
•If the data on each input line represents a valid postflx expression,
the program works. • one of several actions (for example, halt execution or print erroneous
results).
• Suppose that at the final statement of the program, the stack opndstk
is not empty.
•We get no error messages (because we asked for none), and eval
returns a numerical value for an expression that was probably,
incorrectly stated in the first place.
- Infix to Postfix Conversion using Stack Data Structure:
To convert Infix Expression into Postfix Expression using a stack data structure, We can use the
following steps.
Step 1: Start
Step 2: Read all the symbols one by one from left to right in the given Infix Expression.
Step 3: If the reading symbol is operand, then directly print in the result (Output).
Step 4: If the reading symbol is left parenthesis '(', then Push it on to the Stack.
Step 5: If the reading symbol is right parenthesis ')', then Pop all the contents of stack until
respective left parenthesis is poped and print each poped symbol to the result.
Step 6: If reading symbol is operator whose precedence is lower or equal than current stack
operator then pop operators from stack and print in the result.
Step 7: Repeat step 3 to Step 6 untill input expression End.
Step 8: Stop

Example:
Convert A+(B*C) into Postfix form

Postfix Expression: ABC*+


- Infix to Prefix Conversion using Stack Data Structure:
To convert Infix Expression into Prefix Expression using a stack data structure, We can use the
following steps.
Given input Infix Expression: A+(B*C)
Step 1: Reverse the given infix expression.
)C*B(+A
Step 2: Make every ‘(‘ as ‘)’ and every ‘)’ as ‘(‘.
(C*B)+A
Step 3: Convert Step 2 expression into Postfix form.

Step 4: Reverse the postfix expression.


Prefix Expression: + A * B C
- Postfix Expression Evaluation: Below steps are required to evaluate postfix expression.
Step 1: Scan postfix expression from left to right
Step 2: If reading symbol is operand then PUSH it on to stack.
Step 3: If reading symbol is operator then POP two values from stack and perform the operations
between them and again push result back onto stack.
Note: First pop value become second operand and second pop value become first operand
in expression.
Step 4: Repeat above all steps until input expression End.

Examples:
- Prefix Expression Evaluation: Below steps are required to evaluate prefix expression.
Step 1: Scan prefix expression from right to left.
Step 2: If reading symbol is operand then PUSH it on to stack.
Step 3: If reading symbol is operator then POP two values from stack and perform the operations
between them and push result back onto stack.
Note: First pop value become first operand and second pop value become second operand
in expression.
Step 4: Repeat above all steps until input expression End.

Examples:

Program to evaluate a Postfix expression

#include <stdio.h>

#include <ctype.h> // For isdigit()

#define MAX 100

int stack[MAX];

int top = -1;


void push(int x) {

stack[++top] = x;

int pop() {

return stack[top--];

int evaluatePostfix(char* exp) {

for (int i = 0; exp[i] != '\0'; i++) {

if (isdigit(exp[i])) {

push(exp[i] - '0'); // Push the operand (as int)

} else {

int val2 = pop();

int val1 = pop();

switch (exp[i]) {

case '+': push(val1 + val2); break;

case '-': push(val1 - val2); break;

case '*': push(val1 * val2); break;

case '/': push(val1 / val2); break;

}
}

return pop();

int main() {

char exp[MAX];

printf("Enter a postfix expression: ");

scanf("%s", exp);

printf("The result is: %d\n", evaluatePostfix(exp));

return 0;

}
- limitations of the provided C program for evaluating postfix expressions:

1. Single-Digit Operands Only:


o The program only handles single-digit operands (0-9). It does not support multi-
digit numbers.
2. No Error Handling for Invalid Expressions:
o The program does not handle errors or invalid postfix expressions, such as
mismatched operators and operands, or division by zero.
3. Limited Operator Support:
o It only supports basic arithmetic operators: +, -, *, and /. It cannot handle other
operators or functions.
4. Assumes Well-Formed Input:
o The program assumes that the input is a well-formed postfix expression with no
spaces or special characters other than the operators.
5. No Input Validation:
o There is no validation for non-numeric characters or incorrect formats in the input.
6. Stack Size Limitation:
o The program uses a fixed-size stack (MAX 100), so it may not handle very large
expressions or deeply nested operations if the stack size limit is exceeded.
7. Does Not Handle Floating-Point Numbers:
o The program only works with integer arithmetic and does not support floating-
point numbers.
8. No Handling of White Spaces:
o The program assumes no spaces between operands and operators. It does not
handle input with spaces or other delimiters.
- The queue and its sequential representation,
•A queue is an ordered collection of items from which items may be
deleted at one end (called the front of the queue) and into which
items may be inserted at the other end (called rear of te queue.

 Queue is a linear data structure in which the insertion and deletion operations are performed at
two different ends.
 Queue data structure is a collection of similar data items in which insertion and deletion
operations are performed based on FIFO or LILO manner.
 In a queue data structure, adding and removing of elements are performed at two different
positions.
 The insertion is performed at one end and deletion is performed at other end.
 In a queue data structure, the insertion operation is performed at a position which is known as
'rear' and the deletion operation is performed at a position which is known as 'front'.
 In queue data structure, the insertion and deletion operations are performed based on FIFO (First
In First Out) or LILO (Last In Last Out) manner.

Below diagram shows the behavior of a stack:


 In the above figure, insertion and deletion operations are performed at two different end of the

queue.
 Rear end is used for inserting an new element and Front end is used for deleting an element from
the queue.
 Front Variable: While implementing the queue data structure, front variable is important which
is an integer type. Front is a variable which hold the index of the element that is to be deleted.
The initial value of front variable is -1.
 Rear Variable: While implementing the queue data structure, rear variable is important which is
an integer type. Rear is a variable which hold the index of the element that has been inserted. The
initial value of rear variable is -1.

 Example:
If we want to create a queue by inserting 25,30,51,60 and 85. Then rear points to 85 element and
front point to 25 element of array as mentioned in below:
- The queue as an ADT.

-
- Priority Queue:
 Priority queue is a one of the types of queue.
 Priority Queue is a linear data structure.
 The rules for processing the elements of priority queue are:
1. Elements are processed based on priority.
2. Highest priority elements are processed first before the lowest priority elements.
3. If two elements have the same priority, they are processed in FIFO manner.
Example of priority queue:
 Hospital waiting room where emergency patient admitted first before the normal patient.
 Operating system scheduler
 Routing
 Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s Minimum Spanning Tree, etc
Operations on a Priority Queue: The following operations are performed on the Priority Queue.
1. Initialize – To initialize the priority queue, in this operation -1 value set to rear and front
variables.
2. Empty – To check whether priority queue is empty or not.
3. Full – To check whether the priority queue is full or not.
4. Insertion– To insert the new element into the priority queue using rear end.
5. Deletion – To delete the element from the priority queue using front end on the basis of
priority.
6. Print – To display all elements of the priority queue.

You might also like