Sei sulla pagina 1di 100

Data Structures

3ST Technologies – Confidential C & DS 1


Introduction to data structure
➢Data structure deals with the study of how the data is
organized in the memory, how efficiently data can be retrieved
or manipulated and the possible way in which different data
items are logically related.
➢A data structure is a specialized format for organizing and
storing data. General data structure types include the array,
the file, the record, the table, the tree, and so on.
➢ Any data structure is designed to organize data to suit a
specific purpose so that it can be accessed and worked with in
appropriate ways.
➢In computer programming, a data structure may be selected or
designed to store data for the purpose of working on it with
various algorithms.

3ST Technologies – Confidential C & DS 2


Contents DS
• Sorting
- bubble, selection, insertion, quick, heap, merge sort
• Searching
- Linear/sequential search
- Binary search
• Linked lists
- Simple, Circular, Doubly linked list
• Stack & Queue
- arrays, linked lists, circular, priority
• Trees
- binary, tree traversal – in, pre, post order
- spanning tree – DFS, BFS
• Graphs
- directed, weighted, un-directed
3ST Technologies – Confidential C & DS 3
Sorting
• Arranging elements in ascending or descending order using
different algorithms is called sorting.

• There are various algorithms by which we can order the list of


elements given below-

1. Bubble sort
2. Selection sort
3. Quick sort
4. Insertion sort etc…

3ST Technologies – Confidential C & DS 4


Bubble Sort

• Bubble sort works by comparing two items in the


list at a time and swap them if they are out of order.

• If we assume that we start at the beginning of the


list, this means that at each pass through the
algorithm, the largest remaining item in the list will
be placed at its proper location in the list.

3ST Technologies – Confidential C & DS 5


Bubble Sort Algorithm
Step 1: Repeat Steps 2 and 3 for i=1 to 10

Step 2: Set j=1

Step 3: Repeat while j<=n


(A) if a[i] < a[j]
Then interchange a[i] and a[j]
[End of if]

(B) Set j = j+1


[End of Inner Loop]

[End of Step 1 Outer Loop]

Step 4: Exit
3ST Technologies – Confidential C & DS 6
Example – Bubble Sort
Sort the list {15, 4, 23, 12, 56, 2} using bubble sort.

1. Compare 15 and 4 : 4 is smaller, so swap 15 and 4


Compare 15 and 23 : no swap
Compare 23 and 12 : 12 is smaller, so swap 23 and 12
Compare 23 and 56 : no swap
Compare 56 and 2 : 2 is smaller, so swap 56 and 2
End of list : List is now {4, 15, 12, 23, 2, 56} and 56 is in its proper position.

2. Compare 4 and 15 : no swap


Compare 15 and 12 : 12 is smaller, so swap 15 and 12
Compare 15 and 23 : no swap
Compare 23 and 2 : 2 is smaller, so swap 23 and 2
End of list : List is now {4, 12, 15, 2, 23, 56} and 23 is in its proper position.
3ST Technologies – Confidential C & DS 7
Example – Bubble Sort Continue….
3. Compare 4 and 12 : no swap
Compare 12 and 15 : no swap
Compare 15 and 2 : 2 is smaller, so swap 15 and 2
End of list : List is now {4, 12, 2, 15, 23, 56} and 15 is in its proper position.

4. Compare 4 and 12 : no swap


Compare 12 and 2 : 2 is smaller, so swap 12 and 2
End of list : List is now {4, 2, 12, 15, 23, 56} and 12 is in its proper position.

5. Compare 4 and 2 : 2 is smaller, so swap 4 and 2


End of list : List is now {2, 4, 12, 15, 23, 56}, and everything is in place.

Finished! Sorted list is {2, 4, 12, 15, 23, 56}.

3ST Technologies – Confidential C & DS 8


Performance of bubble sort
• The best case for bubble sort occurs when the list is already sorted. In
this case, bubble sort makes one pass through the list, performing no
swaps and N-1 comparisons.

• The worst case for bubble sort occurs when the list is in reverse order. In
this case, every item will have to be swapped with every other item on
every pass through the algorithm. As in selection sort, there will be
O(N2) comparisons. The number of swaps in the worst case is greater
than in selection sort: each comparison results in a swap, so there are
O(N2) swaps in bubble sort!

• The average case looks like the worst case: O(N2) comparisons and O(N2)
swaps. The tradeoff is that we may be able to do half as many iterations,
on average, as we do in selection sort. From a mathematical standpoint,
however, bubble sort performs worse than selection sort in terms of the
number of swaps, and the same as selection sort in terms of the number
of comparisons.
3ST Technologies – Confidential C & DS 9
Example – Bubble Sort
#include <stdio.h>
main() {
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++) {
for (d = 0 ; d < n - c - 1; d++) {
if (array[d] > array[d+1]) { /* For decreasing order use < */
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
}
3ST Technologies – Confidential C & DS 10
Selection Sort
• We put the smallest item at the start of the list, then the next smallest
item at the second position in the list, and so on until the list is in order.
Algorithm
for i=0 to N-2
{
smallest = list item at index i
for j=i+1 to N-1
{
if item at position j < smallest
smallest = list item at index j
}
swap current item with smallest item found
}
3ST Technologies – Confidential C & DS 11
Example – Selection Sort
Sort the list {15, 4, 23, 12, 56, 2} using selection sort.
1. Current item = 15, Smallest = 15
Compare 15 and 4 : 4 is smaller, so set smallest = 4
Compare 4 and 23 : 4 is smaller
Compare 4 and 12 : 4 is smaller
Compare 4 and 56 : 4 is smaller
Compare 4 and 2 : 2 is smaller, so set smallest = 2
End of list : swap 15 and 2
List is now {2, 4, 23, 12, 56, 15} and 2 is in its proper position.
2. Current item = 4, Smallest = 4
Compare 4 and 23 : 4 is smaller
Compare 4 and 12 : 4 is smaller
Compare 4 and 56 : 4 is smaller
Compare 4 and 15 : 4 is smaller
End of list : nothing to swap. List is same as in previous step and both 2 and 4
are in their proper positions.
3ST Technologies – Confidential C & DS 12
Example – Selection Sort Continue…
3. Current item = 23, Smallest = 23
Compare 23 and 12 : 12 is smaller, so set smallest = 12
Compare 12 and 56 : 12 is smaller
Compare 12 and 15 : 12 is smaller
End of list : swap 23 and 12
List is now {2, 4, 12, 23, 56, 15}.
4. Current item = 23, Smallest = 23
Compare 23 and 56 : 23 is smaller
Compare 23 and 15 : 15 is smaller, so set smallest = 15
End of list : swap 23 and 15
List is now {2, 4, 12, 15, 23, 56}
5. Current item = 23, Smallest = 23
Compare 23 and 56 : 23 is smaller
End of list : nothing to swap. List is same as in previous step.
Finished! Sorted list is {2, 4, 12, 15, 23, 56}.
3ST Technologies – Confidential C & DS 13
Performance of selection sort
• The best case for selection sort occurs when the list is already sorted. In this
case, the number of swaps is zero. We still have to compare each item in the
list to each other item in the list on each pass through the algorithm.
• The first time through, we compare the first item in the list to all other items
in the list, so the number of comparisons is (N-1).
• The second time through, we compare the second item in the list to the
remaining items in the list, so the number of comparisons is (N-2).
• The total number of comparisons is (N − 1) + (N − 2) + ... + 2 + 1. This equation
simplifies to N(N + 1)/2 − 1, which is approximately N2. Thus, even in the best
case, selection sort requires O(N2) comparisons.
• The worst case for selection sort occurs when the first item in the list is the
largest, and the rest of the list is in order. In this case, we perform one swap
on each pass through the algorithm, so the number of swaps is N. The
number of comparisons is the same as in the best case, O(N2).
• The average case requires the same number of comparisons, O(N2), and
roughly N/2 swaps. Thus, the number of swaps in the average case is O(N).
• In summary, we say that selection sort is O(N) in swaps and O(N2) in
comparisons.
3ST Technologies – Confidential C & DS 14
Example – Selection Sort
main() {
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ ) {
position = c;
for ( d = c + 1 ; d < n ; d++ ) {
if ( array[position] > array[d] )
position = d;
}
if ( position != c ) {
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
}
3ST Technologies – Confidential C & DS 15
Insertion Sort
It is simplest sorting algorithm which sort the array by shifting
elements one by one. Following are some important
characteristics of insertion sort

1. It is efficient for smaller data sets but very inefficient for


larger data sets.

2. Insertion sort is adaptive, that means it reduces its total no.


of Steps, if given partially sorted list, hence increase
efficiency.

3. It is stable as it does not change the relative order of


elements with equal key.
3ST Technologies – Confidential C & DS 16
How insertion sort works

3ST Technologies – Confidential C & DS 17


Example – Insertion Sort
main() {
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
for (c = 1 ; c <= n - 1; c++) {
d = c;
while ( d > 0 && array[d] < array[d-1]) {
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) {
printf("%d\n", array[c]);
}
}
3ST Technologies – Confidential C & DS 18
Complexity analysis of Insertion Sort

• Worst case time complexity:- O(n2)

• Best case time complexity:- O(n)

• Average time complexity:- O(n2)

• Space complexity:- O(1)

3ST Technologies – Confidential C & DS 19


Quick Sort
• Quick sort, as the name suggest, sort any list very quickly.
Quick sort is not stable sort but is very fast and requires very
less additional space.

• It is based on rule divide and conquer(also called partition


and exchange sort).

• This algorithms divide the list into three main part

1. elements less than the pivot element


2. pivot
3. elements greater than the pivot element

3ST Technologies – Confidential C & DS 20


Example – Quick Sort
void quicksort(int x[10], int first, int last) {
#include<stdio.h> int pivot,j,temp,i;
void quicksort(int [10],int,int); if(first<last){
int main(){ pivot=first;
i=first;
int x[20], size, i; j=last;
while(i<j) {
printf("Enter size of the array: "); while(x[i]<=x[pivot]&&i<last)
i++;
scanf("%d", &size); while(x[j]>x[pivot])
printf("Enter %d elements: ", size); j--;
for(i=0;i<size;i++) if(i<j) {
temp=x[i];
scanf("%d", &x[i]); x[i]=x[j];
x[j]=temp;
quicksort(x, 0, size-1); }
}
temp=x[pivot];
printf("Sorted elements: "); x[pivot]=x[j];
for(i=0;i<size;i++) x[j]=temp;
quicksort(x, first, j-1);
printf(" %d", x[i]); quicksort(x, j+1, last);
return 0; }
} }
3ST Technologies – Confidential C & DS 21
Searching
Sequential Search-

• The simplest search algorithm is sequential search, also


known as Linear search.

• In sequential search, we look at each item in the list in turn,


quitting once we find an item that matches the search term
or once we’ve reached the end of the list. Our return value is
the position in the list at which the search term was found,
or some indicator that the search term was not found in the
list.

3ST Technologies – Confidential C & DS 22


Algorithm – Linear Search

for (each item in list)


{
compare search term to current item
if match,
save index of matching item
break
}
return index of matching item, or -1 if item not found

3ST Technologies – Confidential C & DS 23


Example – Linear Search
main() {
int array[100], search, c, n, count = 0;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d numbers\n", n);
for ( c = 0 ; c < n ; c++ );
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) {
printf("%d is present at location %d.\n", search, c+1);
count++;
}
}
if (count == 0)
printf("%d is not present in array.\n", search);
else
printf("%d is present %d times in array.\n", search, count);
}
3ST Technologies – Confidential C & DS 24
Binary Search
➢Binary search exploits the ordering of a list. The idea behind binary search is
that each time we make a comparison, we eliminate half of the list, until we
either find the search term or determine that the term is not in the list.

➢We do this by looking at the middle item in the list, and determining if our
search term is higher or lower than the middle item.

➢If it’s lower, we eliminate the upper half of the list and repeat our search
starting at the point halfway between the first item and the middle item.

➢If it’s higher, we eliminate the lower half of the list and repeat our search
starting at the point halfway between the middle item and the last item.

➢We repeat this until we either find the item in the list or we’ve ruled out
every possible place that the item could be if it were in the list.

3ST Technologies – Confidential C & DS 25


Algorithm – Binary Search
set first = 1, last = N, mid = N/2
while (item not found and first < last)
{
compare search term to item at mid
if match
save index
break
else if search term is less than item at mid,
set last = mid-1
else
set first = mid+1
set mid = (first+last)/2
}
return index of matching item, or -1 if not found
3ST Technologies – Confidential C & DS 26
Example – Binary Search
main() {
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0; last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
} else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
}
3ST Technologies – Confidential C & DS 27
Linked Lists - Introduction
• To store Records we need List.
• An array is an example of List (set of elements).
• In an array elements are sequentially organized.
• We use index to sequentially access & manipulate these
elements.
• Consider example int number[10];
• We need to specify the size of the array in the beginning itself.
• Contiguous memory cells are required.
• This list may grow as more elements are added.
• Hence more space need to be allocated which is not possible
with arrays.
• Arrays do not suffice here, Linked lists are required for this
purpose
3ST Technologies – Confidential C & DS 28
Linked Lists
• To overcome the disadvantages of arrays, Linked list is another
way of representing a list (set of elements).
• In Linked List space for new record is allocated dynamically.
• Each Element is stored as a Structure unit that also contains a
link (pointer to next element) to the structure containing the
next item.
➢A linked list is a collection of zero or more nodes where each
node has some information.
➢Between each node in the list, there exists a logical
relationship so that given the address of the first node, any
node in that list can be accessed or obtained.
➢Each node hold the data along with a pointer field using
which address of the next node can be obtained.

3ST Technologies – Confidential C & DS 29


Types of Linked Lists

• The different types of linked lists are:

➢Singly Linked Lists

➢Circular Linked Lists

➢Doubly Linked Lists

3ST Technologies – Confidential C & DS 30


Singly Linked Lists
• A singly linked list is a linked list, where each node has
designated field called link field which contains address of
next node.

• If there exists only one link field in each and every node in
the list, then linked list is called singly linked list.

• Memory representation of singly linked list is as shown


below:
info link info link info link info link info link
50 1020 20 1012 45 1008 10 1016 80 Null
node
First=1004 1020 1012 1008 1016

3ST Technologies – Confidential C & DS 31


Singly Linked Lists – Basic Definitions

• A sample Structure definition for a singly linked list node

struct node {
int info;
struct node *link;
};
typedef struct node *NODE;

•This type of structure are called self-referential structures,


which contain a member field that points to the same
structure type.

3ST Technologies – Confidential C & DS 32


Singly Linked Lists – Basic Definitions
• Function to obtain a new node
NODE getnode() {
NODE x;
x=(NODE malloc(sizeof(struct node));
if(x==NULL) {
printf(“Out of memory\n”);
exit(0);
}
return x;
}
• Function to return allocated memory
void freenode(NODE x) {
free(x);
}

3ST Technologies – Confidential C & DS 33


Singly Linked Lists - Operations

• Inserting a node into the list.

• Deleting a node from the list.

• Displaying the contents of a list.

3ST Technologies – Confidential C & DS 34


Singly Linked Lists
• Inserting a node at the front of the linked list

temp 50

first 20 45 10 80

After inserting

50 20 45 10 80

• Function to insert a node at the front of the list


NODE insert_front(int item, NODE first) {
NODE temp;
temp=getnode();
temp->info=item;
temp->link=first;
return temp;
}
3ST Technologies – Confidential C & DS 35
Singly Linked Lists
• Deleting a node from the front of the linked list
temp
50 20 45 10 80
first
first

temp 50 20 45 10 80

first 20 45 10 80

• Function to delete a node from the front of the list


NODE delete_front(NODE first) {
NODE temp; if(temp == NULL) {
printf(“List is empty cannot delete\n”);
return first;
}
temp=first; first=first->link;
printf(“The item deleted is %d\n”, temp->info);
freenode(temp);
return first;
}
3ST Technologies – Confidential C & DS 36
Singly Linked Lists
• Displaying the contents of a singly linked list

void display(NODE first) {


NODE temp;
if(first == NULL)
{
printf(“List is empty\n”);
return;
}
printf(“The contents of singly linked list\n”);
temp=first;
while(temp!=NULl)
{
printf(“%d “, temp->info);
temp=temp->link;
}
printf(“\n”);
}
3ST Technologies – Confidential C & DS 37
Singly Linked Lists
• Inserting a node at the rear end of the linked list
first 20 45 10 80
cur
temp
first 20 45 10 80 50

20 45 10 80 50

• Function to insert a node at the rear end of the linked list


NODE insert_rear(int item, NODE first) {
NODE temp, cur;
temp=getnode();
temp->info=item; temp->link=NULL;
if(first==NULL) return temp;
cur=first;
while(cur->link !=NULL) {
cur=cur->link;
}
cur->link = temp;
return first;
}
3ST Technologies – Confidential C & DS 38
Singly Linked Lists
• Deleting a node from the rear end of the linked list
prev cur
first
20 45 10 80 50

prev cur
first 20 45 10 80 50

• Function to delete a node from the rear end of the linked list
NODE delete_rear(NODE first) {
NODE cur, prev;
if(first == NULL) {
printf(“List is empty cannot delete\n”);
return first;
}
if(first->link == NULL) {
printf(“The item to deleted is %d\n”,first->info);
freenode(first);
first = NULL;
return first;
}
3ST Technologies – Confidential C & DS 39
Singly Linked Lists

• Function to delete a node from the rear end of the linked list cont…

prev=NULL;
cur = first;
while(cur->link !=NULL) {
prev=cur;
cur=cur->link;
}
printf(“The item deleted is %d\n”, cur->info);
freenode(cur);
prev->link = NULL:
return first;
}

3ST Technologies – Confidential C & DS 40


Singly Linked Lists
• Deleting a node at a specified position in the linked list
cur
first 10 20 30 40

first=first->link
prev cur
10 20 30 40

prev->link=cur->link
• Function to delete a node at a specified position in the linked list
NODE delete_pos(int pos, NODE first) {
NODE cur;
NODE prev;
int count;
if(first == NULL) {
printf(“List is empty\n”);
return NULL;
}

3ST Technologies – Confidential C & DS 41


Singly Linked Lists
• Function to delete a node at a specified position in the linked list cont…
if(pos == 1) {
cur = first;
first = first->link;
freenode(cur);
return first;
}
prev = NULL;
cur=first;
count=1;
while(cur != NULL && count !=pos) {
prev = cur;
cur = cur->link;
count++;
}
if(cur == NULL) {
printf(“Invalid position specified\n”);
return first;
}
prev->link = cur->limk;
freenode(cur);
return first;
}
3ST Technologies – Confidential C & DS 42
Singly Linked Lists
• Header Node
➢A node present in the beginning of the list, the purpose of which is
used to simplify the design. Such a node is called header node.

➢Usually info field does not contain any information.

➢The info field sometimes contain the total number of nodes


present in the list.

head

count

head 4 45 10 80 50

3ST Technologies – Confidential C & DS 43


Singly Linked Lists
• Insert a node at a specified position in the linked list
prev cur
first 10 20 30 40

35
temp
first 10 20 30 35 40

• Function to insert a node at a specified position in the linked list


NODE insert_pos(int item, int pos, NODE first) {
NODE temp;
NODE prev, cur;
int count;
temp = getnode();
temp->info = item; temp->link = NULL;
if(first == NULL && pos==1) {
return temp;
if(first == NULL) {
printf(“Invalid position\n”);
return first;
}
3ST Technologies – Confidential C & DS 44
Singly Linked Lists
• Function to insert a node at a specified position in the linked list cont…

if(pos == 1) {
temp->link;
return temp;
}
count=1;
prev = NULL;
cur=first;
while(cur != NULL && count !=pos) {
prev = cur;
cur = cur->link;
count++;
}
if(count == pos) {
prev->link = temp;
temp->link = cur;
return first;
}
printf(“Invalid position specified\n”);
return first;
}
3ST Technologies – Confidential C & DS 45
Linked Lists
• Linked list vs. arrays
• Linked list
• Advantage
➢ Constant-time insertion/removal once the insertion/removal
point is known
➢ Allocate nodes dynamically as needed, does not get full.
• Disadvantage
➢ No direct access to elements
➢ Extra storage for links
• Arrays
• Advantage
➢ Direct access to elements (by indexing)
• Disadvantage
➢ Linear time insertion/removal due to shifting
➢ Size is fixed
3ST Technologies – Confidential C & DS 46
Linked Lists
• Limitation of singly linked lists

➢ Can (efficiently) insert a node only after a referenced node

➢ Can (efficiently) remove a node only if we have a reference


to its predecessor node

➢ Can traverse the list only in the forward direction

• Above limitations removed by adding a reference in each node to


the previous node (double-linked list)

3ST Technologies – Confidential C & DS 47


Circular Linked Lists
• Last element links to first element
• Can reach entire list from any node
• Any node can be considered as first node and its predecessor is considered as
last node
last

• The following two conventions can be used to implement a circular


linked list
1. A pointer variable first can be used to designate the starting point of the
list. Using this approach, to get the address of the last node, the entire
list has to be traversed from the first node
2. In the second technique, a pointer variable last can be used to designate
the last node and the node that follow last, can be designated as the
first node of the list. Here, we use the second approach.
3ST Technologies – Confidential C & DS 48
Circular Linked Lists
• Insert a node at the front end in the circular linked list
last

20 45 10 80

temp last
50 20 45 10 80

• Function to insert a node at the front end in the circular linked list
NODE insert_front(int item, NODE last) {
NODE temp;
temp = getnode();
temp->info = item;
if(last == NULL)
last=temp;
else
temp->link = temp;
return last;
}
3ST Technologies – Confidential C & DS 49
Circular Linked Lists
• Insert a node at the rear end in the circular linked list last

50 20 45 10

last temp
50 20 45 10 80

last
50 20 45 10 80

• Function to insert a node at the rear end in the circular linked list
NODE insert_rear(int item, NODE last) {
NODE temp;
temp = getnode();
temp->info = item;
if(last == NULL)
last=temp;
else {
temp->link = last->link; last->link=temp; }
return temp;
}
3ST Technologies – Confidential C & DS 50
Circular Linked Lists
• Deleting a node from the front end in the circular linked list
first last

50 20 45 10 80

• Function to delete a node from the front end in the circular linked list
NODE delete_front(NODE last) {
NODE temp, first;
if(last == NULL) {
printf(“List is empty\n”);
return NULL;
}
if(last->link == last) {
printf(“The item deleted is %d\n”, last->info);
freenode(last);
return NULL;
}
first= last->link;
last->link = first->link;
printf(“The item deleted is %d\n”, first->info);
freenode(first);
return last;
}
3ST Technologies – Confidential C & DS 51
Circular Linked Lists last
• Deleting a node from the rear end in the circular linked list
prev
50 20 45 10 80

• Function to delete a node from the rear end in the circular linked list
NODE delete_rear(NODE last) {
NODE prev;
if(last == NULL) {
printf(“List is empty\n”); return NULL;
}
if(last->link == last) {
printf(“The item deleted is %d\n”, last->info);
freenode(last); return NULL;
}
prev= last->link;
while(prev->link != last)
prev=prev->link;
last->link = first->link;
printf(“The item deleted is %d\n”, first->info);
freenode(last);
return prev;
}
3ST Technologies – Confidential C & DS 52
Circular Linked Lists
• Function to display the contents of a circular linked list
void display(NODE last) {
NODE temp;
if(last == NULL) {
printf(“List is empty\n”);
return;
}
printf(“Contents of the list is \n”);
for(temp=last->link; temp != last; temp=temp->link) {
printf(“%d “, temp->info);
printf(“\n”);
}
}

3ST Technologies – Confidential C & DS 53


Circular Linked Lists
• Function to display the contents of a circular linked list with header node
void display(NODE head) {
NODE temp;
if(head->link == head) {
printf(“List is empty\n”);
return;
}
printf(“Contents of the list is\n”);
for(temp=head->link; temp != head; temp= temp->link) {
printf(“%d “, temp->info);
printf(“\n”);
}
}

3ST Technologies – Confidential C & DS 54


Circular Linked Lists
• Insert a node at the specified position node in the circular linked list
head
prev cur
4 20 45 10 80

temp 50

• Function to insert a node at the specified position node in the circular linked list
insert_position(int item, int pos, NODE head) {
NODE prev, cur, temp;
int i;
if(pos > head->info+1) || (pos<1) {
printf(“Invalid position\n”);
return head;
}
prev=head;
cur=head->link;
for(i=1;i<pos;i++) {
prev=cur; cur=cur->link;
}
temp=getnode(); temp->info=item; prev->link=temp; temp->link=cur; head->info +=1;
return head;
}
3ST Technologies – Confidential C & DS 55
Circular Linked Lists
• Delete a node at the specified position node in the circular linked list

prev cur
head 4 20 45 10 80

• Function to delete a node at the specified position node in the circular linked list
NODE delete_position(int pos, NODE head) {
NODE prev, cur;
int i;
if(head->link == head) {
printf(“List is empty\n”); return head;
}
if(pos > head->info+1) || (pos<1) {
printf(“Invalid position\n”); return head;
}
prev = cur = head;
for(i=1;i<pos;i++) {
prev=cur; cur=cur->link;
}
prev->link = cur->link; freenode(cur);
head->info -=1; return head;
}
3ST Technologies – Confidential C & DS 56
Doubly Linked Lists
• Disadvantages of linked lists
1. Using singly linked lists and circular linked list it is not possible to
traverse the list backwards
2. To find predecessor, it is required to traverse the list from the
first node in case of singly linked list. In case of circular list, the
predecessor can be obtained by traversing the whole list from
the node specified.
• Doubly linked lists
• Here it is possible to traverse the list in forward and backward
direction
• It has two link fields
• The link field which contains the address of the left node is called
left link (llink)
• The link field which contains the address of the right node is
called right link (rlink)
3ST Technologies – Confidential C & DS 57
first
Doubly Linked Lists last

10 30
20 5
Doubly Linked List

first 20 10 30 5

Circular Doubly Linked List

head 10 30 5

Circular Doubly Linked List with header node

head

header node
3ST Technologies – Confidential C & DS 58
Doubly Linked Lists
• Insert a node at the front end of the doubly linked list

cur
head 10 30 5

50 temp

• Function to insert a node at the front end of the doubly linked list
NODE insert_ front(int item, NODE head) {
NODE temp, cur;
temp = getnode();
temp->info = item;
cur = head->rlink;
head->rlink = temp;
temp->llink = head;
temp->rlink = cur;
cur->llink = temp;
return head;
}
3ST Technologies – Confidential C & DS 59
Doubly Linked Lists
• Insert a node at the rear end of the doubly linked list

head
10 30 5 50
temp

• Function to insert a node at the rear end of the doubly linked list
NODE insert_ rear(int item, NODE head) {
NODE temp, cur;
temp = getnode();
temp->info = item;
cur = head->llink;
head->llink = temp;
temp->rlink = head;
temp->llink = cur;
cur->rlink = temp;
return head;
}
3ST Technologies – Confidential C & DS 60
Doubly Linked Lists
• Delete a node at the front end of the doubly linked list

cur next
head
10 30 5

• Function to delete a node at the front end of the doubly linked list
NODE delete_ front(NODE head) {
NODE next, cur;
if(head->rlink == head) {
printf(“Deque is empty\n”);
return head;
}
cur = head->rlink;
next=cur->rlink;
head->rlink = next;
next->llink = head;
printf(“The node to be deleted is %d\n”, cur->info);
freenode(cur);
return head;
}
3ST Technologies – Confidential C & DS 61
Doubly Linked Lists
• Delete a node at the rear end of the doubly linked list

head
20 10 30 5
prev cur

• Function to delete a node at the rear end of the doubly linked list
NODE delete_ rear(NODE head) {
NODE prev, cur;
if(head->llink == head) {
printf(“Deque is empty\n”);
return head;
}
cur = head->llink;
prev=cur->llink;
head->llink = prev;
prev->rlink = head;
printf(“The node to be deleted is %d\n”, cur->info);
freenode(cur);
return head;
}
3ST Technologies – Confidential C & DS 62
Doubly Linked Lists
• Function to insert a node to the right of a specified node of a doubly linked list
NODE insert_right(int item, NODE head) {
NODE temp, cur, next;
if(head->rlink == head) {
printf(“List is empty\n”);
return head;
}
cur=head->rlink;
while(cur != head&& item !=cur->info)
cur=cur->rlink;
if(cur==head) {
printf(Key not found\n”);
return head;
}
next= cur->rlink;
printf(“Enter the item inserted towards right of %d=“, item);
temp = getnode();
scanf(“%d”, &temp->info);
cur->rlink= temp;
temp->llink=cur;
next->llink=temp;
temp->rlink=next;
return head;
}
3ST Technologies – Confidential C & DS 63
Doubly Linked Lists
• Function to insert a node to the left of a specified node of a doubly
linked list
NODE insert_left(int item, NODE head) {
NODE temp, cur, prev;
if(head->rlink == head) {
printf(“List is empty\n”);
return head;
}
cur=head->rlink;
while(cur != head && item != cur->info)
cur=cur->rlink;
if(cur==head) {
printf(Key not found\n”);
return head;
}
prev= cur->llink;
printf(“Enter the item inserted towards left of %d=“, item);
temp = getnode();
scanf(“%d”, &temp->info);
prev->rlink= temp;
temp->llink=cur;
cur->llink=temp;
temp->rlink=next;
return head;
}
3ST Technologies – Confidential C & DS 64
Stack
• Take the example of a cafeteria. The plates are placed one above the
other and every new plate is added at the top. When a plate is required,
it is taken off from the top and is used. We can call this process as
stacking of plates. Stack is therefore an ordered list of similar data type
• A stack is defined as a special type of data structure where items are
inserted from one end called top of stack.
• Here, the last item inserted will be on the top of the stack. Since
deletion is done from the same end, last item inserted is the first item
to be deleted out from the stack. i.e. stack is also called Last In First Out
(LIFO).
• push() function is used to insert an element into the stack and pop() is
used to delete an element from the stack.
• Both insertion and deletion are allowed at only one end of stack.
• Stack is said to be in overflow state when it is completely full and it is
said to be underflow state when it is completely empty.

3ST Technologies – Confidential C & DS 65


Stack
• In a nutshell Stack is an abstract data type with a bounded (predefined)
capacity. it is a simple data structure that allows adding and removing
elements in particular order. Every time an element is added, it goes on
the top of stack, the only element that can be removed is element that
was at the top of stack, just like pile of objects.
• As an example consider inserting items onto a stack

3ST Technologies – Confidential C & DS 66


Stack
• Inserting an item onto the stack is called push operation. Assume 5
items 30, 20, 25, 10 and 40 to be placed onto a stack

• Initially the stack is empty. At that time top points to bottom of stack.

• As items are inserted top pointer is incremented and points to the


topmost item.

• After inserting 40, stack is full. In this condition it is not possible to


insert any new item. This situation is called stack overflow.
3ST Technologies – Confidential C & DS 67
Stack
• Deleting an item from the stack is called pop operation.

• As items are deleted the top pointer is decremented.

• Finally when all items are deleted, top points to bottom of the stack.

• When the stack is empty, it is not possible to delete any item and this
situation is called underflow of stack.
3ST Technologies – Confidential C & DS 68
Stack : Static implementation
#include <stdio.h>
#define MAXSIZE 5

struct stack
{
int stk[MAXSIZE];
int top;
};

typedef struct stack STACK;


STACK s;

void push(void);
void pop(void);
void display(void);

3ST Technologies – Confidential C & DS 69


Stack – Example - Continue….
main () {
int choice; switch (choice) {
int option = 1; case 1 :
push();
s.top = -1; break;
case 2 :
printf ("STACK OPERATION\n"); pop();
break;
while (option) {
case 3 :
printf ("----------------------------------\n"); display();
printf (" 1 --> PUSH \n"); break;
printf (" 2 --> POP \n"); case 4 :
break;
printf (" 3 --> DISPLAY \n");
}
printf (" 4 --> EXIT \n"); printf ("\nDo you want to
printf ("----------------------------------\n"); continue(Type 0 or 1)?\n");
printf ("Enter your choice\n"); scanf ("%d", &option);
}
scanf ("%d", &choice); }
3ST Technologies – Confidential C & DS 70
Stack – Example - Continue….
/* Function to add an element to the stack */
void push () {
int num;
if (s.top == (MAXSIZE - 1)) {
printf ("Stack is Full\n");
}
else {
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
}
3ST Technologies – Confidential C & DS 71
Stack – Example - Continue….
/* Function to delete an element from the stack */
void pop () {
int num;
if (s.top == - 1) {
printf ("Stack is Empty\n");
return (s.top);
}
else {
num = s.stk[s.top];
printf ("\npoped element is = %d ", s.stk[s.top]);
s.top = s.top - 1;
}
// return(num);
}
3ST Technologies – Confidential C & DS 72
Stack – Example - Continue….
/* Function to display the status of the stack */
void display () {
int i;
if (s.top == -1) {
printf ("Stack is empty\n");
}
else {
printf ("\n The status of the stack is \n");
for (i = s.top; i >= 0; i--) {
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}
3ST Technologies – Confidential C & DS 73
Stack – Example - Continue….
/* To insert an integer item */
void push() {
if(top==STACK_SIZE-1) {
printf(“Stack overflow\n”);
return;
}
s[++top]=item;
}
/* To insert an integer item (by passing parameters) */
void push(int item, int *top, int s[ ]) {
if(*top==STACK_SIZE-1) {
printf(“Stack overflow\n”);
return;
}
s[++(*top)]=item;
}
3ST Technologies – Confidential C & DS 74
Stack – Example - Continue….
/* To insert an character item (by passing parameters) */
void push(int item, int *top, char s[ ]) {
if(*top==STACK_SIZE-1) {
printf(“Stack overflow\n”);
return;
}
s[++(*top)]=item;
}
/* To delete an integer item */
int pop() {
int item_deleted;
if(top == -1)
return 0;
item_deleted= s[top--];
retrun item_deleted;
}
3ST Technologies – Confidential C & DS 75
Stack – Example - Continue….
/* To delete an integer item (by passing parameters) */
int pop(int *top, int s[ ]) {
int item_deleted;
if(*top == -1)
return 0;
item_deleted= s[(*top)--];
retrun item_deleted;
}
/* To delete an character item (by passing parameters) */
int pop(int *top, char s[ ]) {
int item_deleted;
if(*top == -1)
return 0;
item_deleted= s[(*top)--];
retrun item_deleted;
}
3ST Technologies – Confidential C & DS 76
Stack – Example - Continue….
void display() { /* C function for displaying the contents of stack */
int i;
if(top == -1) {
printf(“Stack empty\n”); return;
}
printf(“Contents of the stack\n”);
for(i=0;i<=top;i++)
printf(“%d\n”, s[i]);
}
void display(int top, int s[]) { /* C function for displaying the contents of stack [by passing parameter] */
int i;
if(top == -1) {
printf(“Stack empty\n”); return;
}
printf(“Contents of the stack\n”);
for(i=0;i<=top;i++)
printf(“%d\n”, s[i]);
}
3ST Technologies – Confidential C & DS 77
Application of Stack
• Conversion of expressions: When we write mathematical
expressions in a program, we use infix expressions. These
expressions will be converted into equivalent machine instructions
by the compiler using stacks. Using stacks, we can efficiently
convert the expressions from infix to postfix, infix to prefix, postfix
to infix, postfix to prefix, postfix to infix and postfix to prefix.

• Evaluation of expressions: An arithmetic expression represented


in the form of either postfix or prefix can be easily evaluated

• Recursion: A function which calls itself is called recursive function

• Other Applications: There are so many applications where stacks


can be used e.g. to find out whether the string is palindrome, to
check whether a given expression is valid or not, etc.

3ST Technologies – Confidential C & DS 78


Application of Stack
• Conversion of expressions:
• Arithmetic expression can be classified into 3 categories:

• Infix expression: An expression having an operator in


between two operands is called infix expression. The infix
expression can be parenthesized or un-parenthesized.
• Example: ((6-(3+2)*5)^2+3), (a+b+c)/2, a*b/2, etc.

• Postfix expression: An expression where an operator follows


the two operands is a postfix expression.
• Example: 632+5*-2^3+, ab+c+2/ , ab*2/

• Prefix expression: An expression where the operator


precedes the two operands is a prefix expression.
• Example: +^-6*+32523, /++abc2, /*ab2

3ST Technologies – Confidential C & DS 79


Application of Stack
• Conversion of expressions:
• Conversion from infix to postfix
((A+(B-C)*D)^E+F) Infix Postfix
((A+T1*D)^E+F) Where T1=B-C BC-
((A+T2)^E+F) Where T2=T1*D T1 D*
(T3^E+F) Where T3=A+T2 A T2+
(T4+F) Where T4=T3^E T3 E^ T4
T5 Where T5=T4+F F+

Substituting T5
T4 F + T3 E^ F +
A T2 + E ^ F +
A T1 D * + E ^ F +
ABC–D*+E^F+

3ST Technologies – Confidential C & DS 80


Application of Stack
• Conversion of expressions:
• Conversion from infix to prefix
((A+(B-C)*D)^E+F) Infix Prefix
((A+T1*D)^E+F) Where T1=B - C - BC
((A+T2)^E+F) Where T2=T1 * D * T1 D
(T3^E+F) Where T3=A + T2 + A T2
(T4+F) Where T4=T3 ^ E Where ^ T3 E
T5 T5=T4 + F + T4 F
Substituting
+ T4 F
+ ^ T3 E F
+ ^ + A T2 E F
+ ^ + A * T1 D E F
+^+A*-BCDEF
3ST Technologies – Confidential C & DS 81
Application of Stack
• Evaluation of expressions
Postfix Expression
Symbol Op2 Op1 Result= Op1 Stack
scanned op Op2 Contents
632–5*+1^7+ 6 6
32–5*+1^7+ 3 63
2–5*+1^7+ 2 632
–5*+1^7+ - 2 3 3-2=1 61
5*+1^7+ 5 615
*+1^7+ * 5 1 5*1=5 65
+1^7+ + 5 6 5+6=11 11
1^7+ 1 11 1
^7+ ^ 1 11 1^11=11 11
7+ 7 11 7
+ + 7 11 11+7 18

3ST Technologies – Confidential C & DS 82


Queues
• Queue is an abstract data type or a linear data structure, in which the first
element is inserted from one end called REAR(also called tail), and the
deletion of existing element takes place from the other end called
as FRONT(also called head).
• This makes queue as FIFO data structure, which means that element
inserted first will also be removed first.
• The process to add an element into queue is called Enqueue and the
process of removal of an element from queue is called Dequeue.

3ST Technologies – Confidential C & DS 83


Queues
• Different types of queue
• Ordinary Queue
0 1 2 3 4
delete 10 20 30 Insert
Front end Rear end

• Double ended Queue


0 1 2 3 4
if (f==0 && r==-1)
q[++r]=item;

r f 2 3
0 1 2 3 4
• Circular Queue 10

f 4
r 1
10
0
• Priority Queue
f, r
3ST Technologies – Confidential C & DS 84
Queues – Example
#include <stdio.h> switch (choice) {
#define MAX 50 case 1:
int queue_array[MAX]; Enqueue();
int rear = - 1, front = - 1; break;case 2:
void Enqueue(); Dequeue();
void Dequeue(); break;
void display();
case 3:
main() {
int choice; display();
while (1) { break;
printf("1. Insert element to queue \n"); case 4:
printf("2. Delete element from queue \n"); break;
printf("3. Display all elements of queue \n"); default:
printf("4. Quit \n"); printf("Wrong choice \n");
printf("\n"); } /*End of switch*/
printf("Enter your choice : "); } /*End of while*/
scanf("%d", &choice);
} /*End of main()*/

3ST Technologies – Confidential C & DS 85


Queues – Example – Continue….
void Enqueue() {
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else {
if (front == -1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*End of insert()*/
3ST Technologies – Confidential C & DS 86
Queues – Example – Continue….
void Dequeue() {
if (front == - 1 || front > rear)
printf("Queue Underflow \n");
else {
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /*End of delete() */
void display() {
int i;
if (front == - 1)
printf("Queue is empty \n");
else {
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n"); }
}
3ST Technologies – Confidential C & DS 87
Queues – Example – Continue….
0 1 2 3 4
10 20 30 40

f r
After inserting 50
10 20 30 40 50

f r
• Function to check whether the queue is full
int qfull (int r) {
return (r == QUEUE_SIZE-1)?1:0;
}
• Function to check for underflow of queue
int qempty(int f,int r) {
return(f>r)?1:0;
}
3ST Technologies – Confidential C & DS 88
Queues – Example – Continue….
10 20 30 40

f r

20 30 40

f r
50

f,r
• Function to display the contents of queue
void display(int q[ ],int f,int r) {
int i;
if(qempty(f, r)) {
printf(“Queue is empty\n”);
return;
}
printf(“Contents of queue is\n”);
for(i=f;i<=r;i++)
printf(“%d\n”, q[i]);
}
3ST Technologies – Confidential C & DS 89
Queues – Example – Continue….
• Function to insert an item at the rear end of queue
void insert_rear(int item.int q[ ], int *r)v{
if(qfull(*r)) {
printf(“Queue overflow\n”);
return;
}
q[++(*r)]=item;
}
• Function to delete an item from the front end
void delete_front(int q[ ], int *f, int *r) {
if(qempty(*f, *r)) {
printf(“Queue underflow\n”);
return;
}
printf(“The element deleted is %d\n”, q[(*f)++]);
if(*f > *r) {
*f = 0;
*r = -1;
}
}
3ST Technologies – Confidential C & DS 90
Queues
• Disadvantages queue
• Consider the queue, when 5 elements say 10, 20, 30, 40 and 50 are
inserted and then deleting first four items 10, 20, 30 and 40. If we try to
insert an element say 60, since r has the value QUEUE_SIZE-1, we get an
overflow condition and it is not possible to insert any element. Even
though queue is not full, in this case, it is not possible to insert any item
into the queue. 0 1 2 3 4
50

f, r

• Disadvantage can be eliminated:


➢ By removing the item at the front end of the queue and then shifting
the data from second locations onwards to their respective previous
locations. But, shifting the data is costly in terms of computer time if
the data being stored is very large.
➢ By using circular queue

3ST Technologies – Confidential C & DS 91


Queues
• Double ended queue (Deque)

• It is a special type of data structure in which insertions and deletions


will be done either at the front end or at the rear end of the queue.
Here, insertion and deletions are done from both the ends. The
operations that can be performed on deques are:
• Insert an item from front end
• Insert an item from rear end
• Delete an item from front end
• Delete an item from rear end
• Display the contents of queue

• The 3 operations insert_rear, delete_front and display and the


operations underflow and overflow of queue are same as in ordinary
queue.

3ST Technologies – Confidential C & DS 92


Queues
• Insert an item from front end

0 1 2 3 4
if (f==0 && r==-1)
q[++r]=item;

r f

0 1 2 3 4
30 40 if (f!=0)
q[--f]=item;

f r

0 1 2 3 4
10 20 30 40 Not possible to insert an
item at the front end

f r

3ST Technologies – Confidential C & DS 93


Queues
• Function to insert an item at the front end
void insert_front(int item, int q[ ], int *f, int *r) {
if(*f==0 && *r==-1) {
q[++(*r)]=item;
return;
}
if(*f!=0) {
q[--(*f)]=item;
return;}
printf(“Front insertion not possible\n”);
}
• Function to delete an item from the rear end
void delete_rear(int q[ ], int *f, int *r) {
if(qempty(*f, *r) {
printf(“Queue underflow\n”);
return;}
printf(“The element deleted is %d\n”, q[(*r)--]);
if(*f > *r) {
*f=0;
*r=-1;
}
}
3ST Technologies – Confidential C & DS 94
Circular Queues
• The disadvantage of ordinary queue is overcome using circular queue.
• Here the elements of a given queue can be stored efficiently in an
array so as to wrap around so that the end of the queue is followed
by front of the queue
0 1 2 3 4 0 1 2 3 4
10 10 20 30

f
r f r After inserting 20 and 30
3 2
3 2 r
30

4 1
10 4 20 1

0 10
0
f, r f

3ST Technologies – Confidential C & DS 95


Circular Queues
• Circular queue

0 1 2 3 4 0 1 2 3 4
10 20 30 40 50 30 40 50

f r
f r
After inserting 40 & 50 After deleting 40 & 50
3
3
40 2 40 2 f
30 30
50 r 4 50
r 4
20 1
10 1
0
f 0

3ST Technologies – Confidential C & DS 96


Circular Queues
• Circular queue
0 1 2 3 4
60 30 40 50 After inserting 60

r f
f
2
• Function to check queue overflow 3
30
40
int qfull (int count) {
return (count == QUEUE_SIZE) ? 1:0; 4 50 1
} 60
0
r
• Function to check queue underflow
int qempty(int count) {
return (count == 0)?1:0;
}

3ST Technologies – Confidential C & DS 97


Circular Queues
• Insert from the rear end Function to insert an item at the rear end
void insert_rear(int item, int q[], int *r, int *count) {
if(qfull(*count)) {
printf(“Overflow of queue\n”);
return;
}
*r = (*r+1) % QUEUE_SIZE;
q[*r] = item;
*count += 1;
}
• Function to delete an item from the front end
void delete-front(int q[ ], int *f, int *count) {
if(qempty(*count)) {
printf(“Underflow of queue\n”);
return;
}
printf(“The deleted element is %d\n”, q[*f]);
*f=(*f + 1) % QUEUE_SIZE;
*count -= 1;
}
3ST Technologies – Confidential C & DS 98
Circular Queues
• To display queue contents Function to display the contents of queue
void display(int q[ ], int f, int count) {
int i, j;
if(qempty(f, r)) {
printf(“Queue is empty\n”);
return;
}
printf(“Contents of queue is\n”);
i=f;
for(j=1;j<=count;j++) {
printf(“%d\n”,q[i]);
i=(i+1)% QUEUE_SIZE;
}
printf(“\n”);
}

3ST Technologies – Confidential C & DS 99


Priority Queues

• The priority queue is a special type of data structure in which items


can be inserted or deleted based on the priority

• Always an element with highest priority is processed before


processing any of the lower priority elements

• If the elements in the queue are of same priority, then the element,
which is inserted first into queue, is processed

• Priority queues are used in job scheduling algorithms in the design of


operating system where the jobs with highest priorities have to be
processed first

3ST Technologies – Confidential C & DS 100

Potrebbero piacerti anche