Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views19 pages

Data Structure

The document provides an overview of searching techniques, specifically linear and binary search, and introduces stack and linked list data structures. It explains stack operations (push and pop), advantages and disadvantages of linked lists, and their various types. Additionally, it discusses postfix expressions, operator precedence, and the importance of data structures in programming, highlighting linear and non-linear data structures and their applications.
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)
4 views19 pages

Data Structure

The document provides an overview of searching techniques, specifically linear and binary search, and introduces stack and linked list data structures. It explains stack operations (push and pop), advantages and disadvantages of linked lists, and their various types. Additionally, it discusses postfix expressions, operator precedence, and the importance of data structures in programming, highlighting linear and non-linear data structures and their applications.
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/ 19

What is Searching

Searching is an operation or a technique that helps finds the place of a given element or value in the
list. Any search is said to be successful or unsuccessful depending upon whether the element that is
being searched is found or not.

Some of the standard searching technique that is being followed in the data structure is listed
below:

• Linear Search or Sequential Search

• Binary Search

Linear search is a very simple search algorithm.

• It has a time complexity of O(n), which means the time is linearly dependent on the number
of elements, which is not bad, but not that good too.

• In this type of search, a sequential search is made over all items one by one.

• Every item is checked and if a match is found then that particular item is returned, otherwise
the search continues till the end of the data collection.

Binary search is a fast search algorithm with run-time complexity of Ο(log n).

• This search algorithm works on the principle of divide and conquer.

For this algorithm to work properly, the data collection should be in the sorted form.

• Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned.

• If the middle item is greater than the item, then the item is searched in the sub-array to the
left of the middle item. Otherwise, the item is searched for in the sub-array to the right of
the middle item.

This process continues on the sub-array as well until the size of the sub array reduces to zero.

First, we shall determine half of the array by using this formula −

mid = (low + high) / 2

Here it is, 0 + 9 / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Then perform the steps written above.


Introduction to Stack Data Structure

A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named
stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc.

A real-world stack allows operations at one end only.

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

Likewise, Stack ADT allows all data operations at one end only. At any given time, we can only access
the top element of a stack.

So, Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

There are many real-life examples of a stack.

Consider an example of plates stacked over one another in the canteen. The plate which is at the top
is the first one to be removed, i.e. the plate which has been placed at the bottommost position
remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In
First Out)/FILO(First In Last Out) order.
Stack Representation

Stack Basic Operations

• push() − Pushing (storing) an element on the stack.

• pop() − Removing (accessing) an element from the stack.

To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the
following functionality is added to stacks –

• isFull() − check if stack is full.

• isEmpty() − check if stack is empty.

Push Operation

The process of putting a new data element onto stack is known as a Push Operation. Push operation
involves a series of steps –

• Step 1 − Checks if the stack is full.

• Step 2 − If the stack is full, produces an error and exit.

• Step 3 − If the stack is not full, increments top to point next empty space.

• Step 4 − Adds data element to the stack location, where top is pointing.

• Step 5 − Returns success.

If the linked list is used to implement the stack, then in step 3, we need to allocate space
dynamically.
Pop Operation

Accessing the content while removing it from the stack, is known as a Pop Operation.

In an array implementation of pop() operation, the data element is not actually removed,
instead top is decremented to a lower position in the stack to point to the next value.

But in linked-list implementation, pop() actually removes data element and deallocates memory
space.

A Pop operation may involve the following steps −

• Step 1 − Checks if the stack is empty.

• Step 2 − If the stack is empty, produces an error and exit.

• Step 3 − If the stack is not empty, accesses the data element at which top is pointing.

• Step 4 − Decreases the value of top by 1.

• Step 5 − Returns success.


Linked List

A linked list data structure includes a series of connected nodes. Here, each node store the
data and the address of the next node.
Linked List is a sequence of links which contains items.
Each link contains a connection to another link.
Linked list is the second most-used data structure after array.

For example,

Each node in a list consists of at least two parts:


1. Data
2. Pointer to the next node

We wrap both the data item and the next node reference in a struct as:
struct node
{
int data;
struct node *next;
};

Following are the important terms to understand the concept of Linked List.
• Linked List contains a start pointer called head.
• Each node carries a data field(s) called Data and a link field called next.
• Each node is linked with its next node using its address.
• Last node carries a link as null to mark the end of the list.

Advantages of Linked Lists


• They are a dynamic in nature which allocates the memory when required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.

Disadvantages of Linked Lists


• The memory is wasted as pointers require extra memory for storage.
• No element can be accessed randomly; it has to access each node sequentially.
• Reverse Traversing is difficult in linked list.

Applications of Linked Lists


• Dynamic memory allocation
• Implemented in stack and queue
• In undo functionality of softwares

• Linked lists are used to implement stacks, queues, graphs, etc.


• Hash tables, Graphs
Types of Linked List
Following are the various types of linked list.
• Simple Linked List − Item navigation is forward only.
• Doubly Linked List − Items can be navigated forward and backward.
• Circular Linked List − Last item contains link of the first element as next and the first
element has a link to the last element as previous.

Basic Operations
Following are the basic operations supported by a list.
• Insertion − Adds an element at the beginning of the list.
• Deletion − Deletes an element at the beginning of the list.
• Display − Displays the complete list.
• Search − Searches an element using the given key.
• Delete − Deletes an element using the given key.

Stack-Postfix Expression
This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to the
operands i.e., the operator is written after the operands.
For example, ab+. This is equivalent to its infix notation a + b.
Sr.No. Infix Notation Prefix Notation Postfix
Notation
1 a+b +ab ab+
2 (a + b)*c *+abc ab+c*
3 a * (b + c) *a + b c abc+*

The Postfix notation is used to represent algebraic expressions. The expressions written in postfix form are
evaluated faster compared to infix notation as parenthesis are not required in postfix.

Parsing Expressions
As it is not a very efficient way to design an algorithm or program to parse infix notations. Instead, these infix
notations are first converted into either postfix or prefix notations and then computed.
To parse any arithmetic expression, we need to take care of operator precedence and associativity also.
Precedence
When an operand is in between two different operators, which operator will take the operand first, is decided
by the precedence of an operator over others.
For example −

As multiplication operation has precedence over addition, b * c will be evaluated first.


Associativity
Associativity describes the rule where operators with the same precedence appear in an expression.
For example, in expression a + b − c, both + and – have the same precedence, then which part of the expression
will be evaluated first, is determined by associativity of those operators.
Here, both + and − are left associative, so the expression will be evaluated as
(a + b) − c.
Precedence and associativity determines the order of evaluation of an expression.
Following is an operator precedence and associativity table (highest to lowest) –

Sr.No. Operator Precedence Associativity


1 Exponentiation ^ Highest Right Associative
2 Multiplication ( * ) & Division ( / ) Second Highest Left Associative

3 Addition ( + ) & Subtraction ( − ) Lowest Left Associative


Evaluation of a Postfix Expression
Suppose p is an arithmetic expression written in postfix notation. The following algorithm, which uses a STACK to held
operands, evaluates P.
We shall now look at the algorithm on how to evaluate postfix notation –
Algorithm
This algorithm finds the value of an arithmetic expression P written in postfix notation
1. Add a right parenthesis “)” at the end of p
2. Scan p from left to right and repeat steps 3 and 4 for each element of p until the right parenthesis ”)”
is encountered.
3. if an operand is encountered, put it on STACK
4. If an operator X is encountered, Then :
•Remove the two top elements of STACK, where A is the top element and B is the next to top element
•Evaluate B X A
•Place the result of (b×a) back on STACK
[End of if structure]
[End of step2 loop]
5. Set value equal to the top element on STACK
6. Exit

Example:
ABC+*DE/-
a=5, B=6,c=2,D=12,E=4
Symbol scanned STACK
A 5
B 5 6
C 562
+ 5 8
* 40
D 40 12
E 40 12 4
/ 40 3
- 37
Introduction to Data Structure Module 1

Data Structure Types

We have two types of data structures:

1.LinearDataStructure

2. Non-linear Data Structure

Linear Data Structures: A data structure is called linear if all of its elements
are arranged in the linear order. In linear data structures, the elements are stored
in non-hierarchical way where each element has the successors and
predecessors except the first and last element.

Types of Linear Data Structures are given below:

Arrays: An array is a collection of similar type of data items and each data item
is called an element of the array. The data type of the element may be any valid
data type like char, int, float or double.

The elements of array share the same variable name but each one carries a
different index number known as subscript. The array can be one dimensional,
two dimensional or multidimensional.

The individual elements of the array age are:

age[0], age[1], age[2], age[3],......... age[98], age[99].


Linked List: Linked list is a linear data structure which is used to maintain a
list in the memory. It can be seen as the collection of nodes stored at non-
contiguous memory locations. Each node of the list contains a pointer to its
adjacent node.

Stack: Stack is a linear list in which insertion and deletions are allowed only at
one end, called top.

A stack is an abstract data type (ADT), can be implemented in most of the


programming languages. It is named as stack because it behaves like a real-
world stack, for example: - piles of plates or deck of cards etc.

Example of Stack

Queue: Queue is a linear list in which elements can be inserted only at one end
called rear and deleted only at the other end called front.

It is an abstract data structure, similar to stack. Queue is opened at both end


therefore it follows First-In-First-Out (FIFO) methodology for storing the data
items.
Non Linear Data Structures: This data structure does not form a sequence i.e.
each item or element is connected with two or more other items in a non-linear
arrangement. The data elements are not arranged in sequential structure.

Types of Non Linear Data Structures are given below:

Trees: Trees are multilevel data structures with a hierarchical relationship


among its elements known as nodes. The bottommost nodes in the hierarchy are
called leaf node while the topmost node is called root node. Each node contains
pointers to point adjacent nodes. Tree data structure is based on the parent-child
relationship among the nodes. Each node in the tree can have more than one
Characteristic Description children except the
leaf nodes whereas
Linear In Linear data structures the data items are arranged in a
each node can
linear sequence. Example: Array have utmost one
parent except the
root node.

Non-Linear In Non-Linear data structures the data items are not in


Graphs: Graphs can
sequence. Example: Tree, Graph be defined as the
pictorial
representation of the
set of elements
Homogeneous In homogeneous data structures, all the elements are of same (represented by
type. Example: Array vertices) connected
by the links known
as edges. A graph is
different from tree in
Non- In Non-Homogeneous data structure, the elements may or the sense that a
Homogeneous may not be of the same type. Example: Structures graph can have cycle
while the tree can
Static Static data structures are those whose sizes and structures
not have the one.
associated memory locations are fixed, at compile time.
Example: Array The data structures
Dynamic Dynamic structures are those which expands or shrinks can also be classified
depending upon the program need and its execution. Also,
their associated memory locations changes. Example: Linked on the basis of the
List created using pointers following
characteristics: yaha
se aage likhna hai
Introduction to Data Structure

A data structure is a special way of organizing and storing data in a computer so


that it can be used efficiently. Array, LinkedList, Stack, Queue, Tree, Graph etc
are all data structures that stores the data in a special way so that we can access
and use the data efficiently. Each of these mentioned data structures has a
different special way of organizing data so we choose the data structure based
on the requirement.Data Structure can be defined as the group of data elements
which provides an efficient way of storing and organising data in the computer
so that it can be used efficiently. Some examples of Data Structures are arrays,
Linked List, Stack, Queue, etc. Data Structures are widely used in almost every
aspect of Computer Science i.e. Operating System, Compiler Design, Artifical
intelligence, Graphics and many more.Data Structures are the main part of many
computer science algorithms as they enable the programmers to handle the
data in an efficient way. It plays a vital role in enhancing the performance of a
software or a program as the main function of the software is to store and
retrieve the user's data as fast as possible.

Basic Terminology

Data structures are the building blocks of any program or the software. Choosing the
appropriate data structure for a program is the most difficult task for a programmer. Following
terminology is used as far as data structures are concerned.
Data: Data can be defined as an elementary value or the collection of values, for example,
student's name and its id are the data about the student.
Group Items: Data items which have subordinate data items are called Group item, for
example, name of a student can have first name and the last name.
Record: Record can be defined as the collection of various data items, for example, if we talk
about the student entity, then its name, address, course and marks can be grouped together to
form the record for the student.
File: A File is a collection of various records of one type of entity, for example, if there are 60
employees in the class, then there will be 20 records in the related file where each record
contains the data about each employee.
Attribute and Entity: An entity represents the class of certain objects. it contains various
attributes. Each attribute represents the particular property of that entity.
Field: Field is a single elementary unit of information representing the attribute of an entity.
Need of Data Structures
As applications are getting complexed and amount of data is increasing day by
day, there may arise the following problems:
Processor speed: To handle very large amount of data, high speed processing is
required, but as the data is growing day by day to the billions of files per entity,
processor may fail to deal with that much amount of data.
Data Search: Consider an inventory size of 106 items in a store, If our
application needs to search for a particular item, it needs to traverse 106 items
every time, results in slowing down the search process.
Multiple requests: If thousands of users are searching the data simultaneously
on a web server, then there are the chances that a very large server can be failed
during that process.
In order to solve the above problems, data structures are used. Data is organized
to form a data structure in such a way that all items are not required to be searched
and required data can be searched instantly.

Why we need data structures? – Advantages of DS

We need data structures because there are several advantages of using them, few
of them are as follows:

1. Data Organization: We need a proper way of organizing the data so that it


can accessed efficiently when we need that particular data. DS provides different
ways of data organization so we have options to store the data in different data
structures based on the requirement.

2. Efficiency: The main reason we organize the data is to improve the efficiency.
We can store the data in arrays then why do we need linked lists and other data
structures? because when we need to perform several operation such as add,
delete update and search on arrays , it takes more time in arrays than some of the
other data structures. So the fact that we are interested in other data structures is
because of the efficiency.

3. Reusability: Data structures are reusable, i.e. once we have implemented a


particular data structure, we can use it at any other place. Implementation of data
structures can be compiled into libraries which can be used by different clients.
4. Abstraction: Data structure is specified by the ADT which provides a level of
abstraction. The client program uses the data structure through interface only,
without getting into the implementation details.
Data Structure Types

We have two types of data structures:

1.LinearDataStructure
2. Non-linear Data Structure

Linear data structures: Elements of Linear data structure are accessed in a


sequential manner, however the elements can be stored in these data structure in
any order. Examples of linear data structure are: LinkedList, Stack, Queue and
Array

Non-linear data structures: Elements of non-linear data structures are stores and
accessed in non-linear order. Examples of non-linear data structure are: Tree and
Graph

Classification of Data Structure with Diagram


Applications of Stack Data Structure

Following are some of the important applications of a Stack data structure:

1. Stacks can be used for expression evaluation.


2. Stacks can be used to check parenthesis matching in an expression.
3. Stacks can be used for Conversion from one form of expression to another.
4. Stacks can be used for Memory Management.
5. Stack data structures are used in backtracking problems.

Expression Evaluation

Stack data structure is used for evaluating the given expression. For example,
consider the following expression
5 * ( 6 + 2 ) - 12 / 4
Since parenthesis has the highest precedence among the arithmetic operators, ( 6 +2
) = 8 will be evaluated first. Now, the expression becomes
5 * 8 - 12 / 4
* and / have equal precedence and their associativity is from left-to-right. So, start
evaluating the expression from left-to-right.
5 * 8 = 40 and 12 / 4 = 3
Now, the expression becomes
40 - 3
And the value returned after the subtraction operation is 37.

Parenthesis Matching

Given an expression, you have to find if the parenthesis is either correctly matched or
not. For example, consider the expression ( a + b ) * ( c + d ).
In the above expression, the opening and closing of the parenthesis are given properly
and hence it is said to be a correctly matched parenthesis expression. Whereas, the
expression, (a + b * [c + d ) is not a valid expression as the parenthesis are incorrectly
given.
Expression Conversion
Converting one form of expressions to another is one of the important applications of
stacks.

• Infix to prefix
• Infix to postfix
• Prefix to Infix
• Prefix to Postfix
• Postfix to Infix
• Postfix to Prefix
Memory management

The assignment of memory takes place in contiguous memory blocks. We call this
stack memory allocation because the assignment takes place in the function call stack.
The size of the memory to be allocated is known to the compiler. When a function is
called, its variables get memory allocated on the stack. When the function call is
completed, the memory for the variables is released. All this happens with the help of
some predefined routines in the compiler. The user does not have to worry about
memory allocation and release of stack variables.
Consider the following snippet:

int main()
{
// All these variables get memory
// allocated on stack
int f;
int a[10];
int c = 20;
int e[n];
}

The memory to be allocated to these variables is known to the compiler and when the
function is called, the allocation is done and when the function terminates, the memory
is released.

Backtracking Problems
Consider the N-Queens problem for an example. The solution of this problem is that N queens should be
positioned on a chessboard so that none of the queens can attack another queen. In the generalized N-Queens
problem, N represents the number of rows and columns of the board and the number of queens which must be
placed in safe positions on the board.
The basic strategy we will use to solve this problem is to use backtracking. In this particular case, backtracking
means we will perform a safe move for a queen at the time we make the move. Later, however, we find that we
are stuck and there is no safe movement for the next Queen, whom we are trying to put on the blackboard, so we
have to go back.
This means we return to the queen's previous move, undo this step, and continue to search for a safe place to
place this queen.
We will use the stack to remember where we placed queens on the board, and if we need to make a backup, the
queen at the top of the stack will be popped, and we will use the position of that queen to resume the search for
next safe location.
Hence, stacks can be used for the allocation of memory for most of the backtracking problems
Infix to Postfix Conversion using Stack

One of the applications of Stack is in the conversion of arithmetic expressions in high-level


programming languages into machine readable form. As our computer system can only understand and
work on a binary language, it assumes that an arithmetic operation can take place in two operands only
e.g., A+B, C*D,D/A etc. But in our usual form an arithmetic expression may consist of more than one
operator and two operands e.g. (A+B)*C(D/(J+D)).
These complex arithmetic operations can be converted into polish notation using stacks which then can
be executed in two operands and an operator form.
Infix Expression
It follows the scheme of <operand><operator><operand> i.e. an <operator> is preceded and succeeded
by an <operand>. Such an expression is termed infix expression. E.g., A+B
Postfix Expression
It follows the scheme of <operand><operand><operator> i.e. an <operator> is succeeded by both the
<operand>. E.g., AB+
Algorithm to convert Infix To Postfix
Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix
expression Y.
1. Push “(“onto Stack, and add “)” to the end of X.
2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto Stack.
5. If an operator is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has
the same precedence as or higher precedence than operator.
2. Add operator to Stack.
[End of If]
6. If a right parenthesis is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is encountered.
2. Remove the left Parenthesis.
[End of If]
[End of If]
7. END.
Let’s take an example to better understand the algorithm
Infix Expression: A+ (B*C-(D/E^F)*G)*H, where ^ is an exponential
operator.

Resultant Postfix Expression: ABC*DEF^/G*-H*+


Advantage of Postfix Expression over Infix Expression
An infix expression is difficult for the machine to know and keep track of
precedence of operators. On the other hand, a postfix expression itself
determines the precedence of operators (as the placement of operators in
a postfix expression depends upon its precedence).Therefore, for the
machine it is easier to carry out a postfix expression than an infix
expression.

You might also like