Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

CSC202 DataStructureANDAgorithm HO

Data structure and algorithm

Uploaded by

emjay2010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

CSC202 DataStructureANDAgorithm HO

Data structure and algorithm

Uploaded by

emjay2010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

What is a Data Structure?

A data structure is a way of organizing the data so that the data can be used efficiently, i.e. it is
concerned with the efficient allocation and manipulation of data. Data structure is a way of defining,
storing & retrieving of data in a structural & systematic way. Data structure is a format for
storing data in a structured manner. It is not a separate programming language. It is just an
implementation method and can be implemented using any one of the programming language
like C, C++, Java, etc. For example, data like photos, videos are stored in gallery with the help
of a data structure.
Different kinds of data structures are suited to different kinds of applications, and some are highly
specialized to specific tasks. For example, B-trees are particularly well-suited for implementation
of databases, while compiler implementations usually use hash tables to look up identifiers.

What are linear and non linear data Structures?


 Linear: A data structure is said to be linear if its elements form a sequence or a linear list.
Examples: Array. Linked List, Stacks and Queues
 Non-Linear: A data structure is said to be non-linear if traversal of nodes is nonlinear in
nature. Example: Graph and Trees.
What are the various operations that can be performed on different Data Structures?
 Insertion: Add a new data item in the given collection of data items.
 Deletion: Delete an existing data item from the given collection of data items.
 Traversal: Access each data item exactly once so that it can be processed.
 Searching: Find out the location of the data item if it exists in the given collection of data
items.
 Sorting: Arranging the data items in some order i.e. in ascending or descending order in
case of numerical data and in dictionary order in case of alphanumeric data.

Various Data Structures


Data structure availability may vary by programming languages. Commonly available data
structures are list, arrays, stack, queues, graph, tree etc.

How is an Array different from Linked List?


 The size of the arrays is fixed; Linked Lists are Dynamic in size.
 Inserting and deleting a new element in an array of elements is expensive, whereas both
insertion and deletion can easily be done in Linked Lists.
 Random access is not allowed in Linked List.
 Extra memory space for a pointer is required with each element of the Linked list.
 Arrays have better cache locality that can make a pretty big difference in performance.

What are some of the applications of Data Structure?


Below are some of the real-time applications of Data Structures
To implement back functionality in the internet web browser.
To store dynamically growing data which is accessed very frequently, based upon a key value.
To implement the undo function in a text editor.
For representing a city region telephone network.
To store information about the directories and files in a system.

1
Advantages of a Linked list over an array
Consider a scenario, where we need to store large amount of data in an array. But, the memory
to store that data is not available contiguously. In this case we cannot use array. Hence, we go for
a linked list. Since each node is connected using link, it is not necessary that memory has to be
contiguous. In addition, some of the major differences between a Linked List and an array are
given below.
Arrays Linked List
Array elements can be accessed randomly Random accessing is not possible in linked
using the array index. lists. The elements will have to be accessed
sequentially.
Data elements are stored in contiguous New elements can be stored anywhere and a
locations in memory. reference is created for the new element using
pointers.

STACK
Stack is a linear data structure which follows the order LIFO (Last In First Out) or FILO (First In
Last Out) for accessing elements. Basic operations of stack are Push, Pop, and Peek
The below operations can be performed on a stack −
 push() − adds an item to stack
 pop() − removes the top stack item
 peek() − gives value of top item without removing it
 isempty() − checks if stack is empty
 isfull() − checks if stack is full
Applications of Stack:
1. Infix to Postfix Conversion using Stack
2. Evaluation of Postfix Expression
3. Reverse a String using Stack
4. Implement two stacks in an array
5. Check for balanced parentheses in an expression

Infix, prefix, Postfix notations


 Infix notation: A + B – Operators are written in-between their operands. This is the usual
way we write expressions. An expression such as
W*(X+Y)/Z
 Postfix notation (also known as “Reverse Polish notation”): X Y + Operators are
written after their operands. The infix expression given above is equivalent to
WXY + * Z/
 Prefix notation (also known as “Polish notation”): + X Y Operators are written before
their operands. The expressions given above are equivalent to
/ * W + XYZ

QUEUE
Queue is a linear structure, which follows the order, is First In First Out (FIFO) to access
elements. Mainly the following are basic operations on queue: Enqueue, Dequeue, Front, and
Rear.
2
The difference between stacks and queues is in removing. In a stack, we remove the item the most
recently added; in a queue, we remove the item the least recently added. Both Queues and Stacks
can be implemented using Arrays and Linked Lists.

The below operations can be performed on a stack −


 enqueue() − adds an item to rear of the queue
 dequeue() − removes the item from front of the queue
 peek() − gives value of front item without removing it
 isempty() − checks if stack is empty
 isfull() − checks if stack is full

Difference between an Array and Stack


Stack Data Structure:
 Size of the stack keeps on changing as we insert and delete the element
 Stack can store elements of different data type
Array Data Structure:
 Size of the array is fixed at the time of declaration itself
 Array stores elements of similar data type

Linked List
A linked list is a linear data structure (like arrays) where each element is a separate object. Each
element (that is node) of a list is comprising of two items – the data and a reference to the next
node.
Types of Linked List :
1. Singly Linked List: In this type of linked list, every node stores address or reference of
next node in list and the last node has next address or reference as NULL. For example 1-
>2->3->4->NULL
2. Doubly Linked List: Here, here are two references associated with each node, one of the
reference points to the next node and one to the previous node. E.g. NULL<-1<->2<->3-
>NULL
3. Circular Linked List: Circular linked list is a linked list where all nodes are connected to
form a circle. There is no NULL at the end. A circular linked list can be a singly circular
linked list or doubly circular linked list. E.g. 1->2->3->1 [The next pointer of last node is
pointing to the first]

Data Structure used for implementing Least Recently Used (LRU) cache
We use two data structures to implement an LRU Cache.
1. Queue , which is implemented using a doubly linked list. The maximum size of the queue
will be equal to the total number of frames available (cache size).The most recently used
pages will be near rear end and least recently pages will be near front end.
2. A Hash with page number as key and address of the corresponding queue node as value.
Heap
A heap can be thought of as a simple tree data structure, however a heap usually employs one of
two strategies:
3
1. min heap; or
2. max heap
Each strategy determines the properties of the tree and its values. If you were to choose the min
heap strategy then each parent node would have a value that is ≤ than its children. For example,
the node at the root of the tree will have the smallest value in the tree. The opposite is true for the
max heap strategy.
Unlike other tree data structures, a heap is generally implemented as an array rather than a series
of nodes, which each have references to other nodes. The nodes are conceptually the same,
however, having at most two children.

The syntax in C++ to create a node in the singly linked list.


struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node));

IMPLEMENTATION OF OPERATIONS ON ABSTRACT DATA TYPES


C++ Program to Implement Doubly Ended Queue
This C++ Program demonstrates operations on Doubly Ended Queue.
Here is source code of the C++ Program to demonstrate Doubly Ended Queue operations. /*
1. * C++ Program To Implement Doubly Ended Queue
2. */
3. #include <iostream>
4. #include <cstdlib>
5. using namespace std;
6. /*
7. * Node Declaration
8. */
9. struct node
10. {
11. int info;
12. node *next;
13. node *prev;
14.
15. }*head, *tail;
16.
17. /*
18. * Class Declaration
19. */
20. class dqueue
21. {
22. public:
4
23. int top1, top2;
24. void insert();
25. void del();
26. void display();
27. dqueue()
28. {
29. top1 = 0;
30. top2 = 0;
31. head = NULL;
32. tail = NULL;
33. }
34. };
35.
36. /*
37. * Main: Contains Menu
38. */
39. int main()
40. {
41. int choice;
42. dqueue dl;
43. while (1)
44. {
45. cout<<"\n-------------"<<endl;
46. cout<<"Operations on Deque"<<endl;
47. cout<<"\n-------------"<<endl;
48. cout<<"1.Insert Element into the Deque"<<endl;
49. cout<<"2.Delete Element from the Deque"<<endl;
50. cout<<"3.Traverse the Deque"<<endl;
51. cout<<"4.Quit"<<endl;
52. cout<<"Enter your Choice: ";
53. cin>>choice;
54. cout<<endl;
55. switch(choice)
56. {
57. case 1:
58. dl.insert();
59. break;
60. case 2:
61. dl.del();
62. break;
63. case 3:
64. dl.display();
65. break;
66. case 4:
67. exit(1);
5
68. break;
69. default:
70. cout<<"Wrong Choice"<<endl;
71. }
72. }
73. return 0;
74. }
75.
76. /*
77. * Insert Element in Doubly Ended Queue
78. */
79. void dqueue::insert()
80. {
81. struct node *temp;
82. int ch, value;
83. if (top1 + top2 >= 50)
84. {
85. cout<<"Dequeue Overflow"<<endl;
86. return;
87. }
88. if (top1 + top2 == 0)
89. {
90. cout<<"Enter the value to be inserted: ";
91. cin>>value;
92. head = new (struct node);
93. head->info = value;
94. head->next = NULL;
95. head->prev = NULL;
96. tail = head;
97. top1++;
98. cout<<"Element Inserted into empty deque"<<endl;
99. }
100. else
101. {
102. while (1)
103. {
104. cout<<endl;
105. cout<<"1.Insert Element at first"<<endl;
106. cout<<"2.Insert Element at last"<<endl;
107. cout<<"3.Exit"<<endl;
108. cout<<endl;
109. cout<<"Enter Your Choice: ";
110. cin>>ch;
111. cout<<endl;
112. switch(ch)
6
113. {
114. case 1:
115. cout<<"Enter the value to be inserted: ";
116. cin>>value;
117. temp = new (struct node);
118. temp->info = value;
119. temp->next = head;
120. temp->prev = NULL;
121. head->prev = temp;
122. head = temp;
123. top1++;
124. break;
125. case 2:
126. cout<<"Enter the value to be inserted: ";
127. cin>>value;
128. temp = new (struct node);
129. temp->info = value;
130. temp->next = NULL;
131. temp->prev = tail;
132. tail->next = temp;
133. tail = temp;
134. top2++;
135. break;
136. case 3:
137. return;
138. break;
139. default:
140. cout<<"Wrong Choice"<<endl;
141. }
142. }
143. }
144. }
145.
146. /*
147. * Delete Element in Doubly Ended Queue
148. */
149. void dqueue::del()
150. {
151. if (top1 + top2 <= 0)
152. {
153. cout<<"Deque Underflow"<<endl;
154. return;
155. }
156. int ch;
157. while (1)
7
158. {
159. cout<<endl;
160. cout<<"1.Delete Element at first"<<endl;
161. cout<<"2.Delete Element at last"<<endl;
162. cout<<"3.Exit"<<endl;
163. cout<<endl;
164. cout<<"Enter Your Choice: ";
165. cin>>ch;
166. cout<<endl;
167. switch(ch)
168. {
169. case 1:
170. head = head->next;
171. head->prev = NULL;
172. top1--;
173. break;
174. case 2:
175. tail = tail->prev;
176. tail->next = NULL;
177. top2--;
178. break;
179. case 3:
180. return;
181. break;
182. default:
183. cout<<"Wrong Choice"<<endl;
184. }
185. }
186. }
187.
188. /*
189. * Display Doubly Ended Queue
190. */
191. void dqueue::display()
192. {
193. struct node *temp;
194. int ch;
195. if (top1 + top2 <= 0)
196. {
197. cout<<"Deque Underflow"<<endl;
198. return;
199. }
200. while (1)
201. {
202. cout<<endl;
8
203. cout<<"1.Display Deque from Beginning"<<endl;
204. cout<<"2.Display Deque from End"<<endl;
205. cout<<"3.Exit"<<endl;
206. cout<<endl;
207. cout<<"Enter Your Choice: ";
208. cin>>ch;
209. cout<<endl;
210. switch (ch)
211. {
212. case 1:
213. temp = head;
214. cout<<"Deque from Beginning:"<<endl;
215. while (temp != NULL)
216. {
217. cout<<temp->info<<" ";
218. temp = temp->next;
219. }
220. cout<<endl;
221. break;
222. case 2:
223. cout<<"Deque from End:"<<endl;
224. temp = tail;
225. while (temp != NULL)
226. {
227. cout<<temp->info<<" ";
228. temp = temp->prev;
229. }
230. temp = tail;
231. cout<<endl;
232. break;
233. case 3:
234. return;
235. break;
236. default:
237. cout<<"Wrong Choice"<<endl;
238. }
239. }
240. }

C++ Program to Implement Stack


This C++ Program demonstrates operations on Stack.
Here is source code of the C++ Program to demonstrate Stack operations.
1. /*
2. * C++ Program To Implement Stack using Linked List
3. */
9
4. #include<iostream>
5. #include<cstdlib>
6. using namespace std;
7.
8. /*
9. * Node Declaration
10. */
11. struct node
12. {
13. int info;
14. struct node *link;
15. }*top;
16.
17. /*
18. * Class Declaration
19. */
20. class stack_list
21. {
22. public:
23. node *push(node *, int);
24. node *pop(node *);
25. void traverse(node *);
26. stack_list()
27. {
28. top = NULL;
29. }
30. };
31.
32. /*
33. * Main: Contains Menu
34. */
35. int main()
36. {
37. int choice, item;
38. stack_list sl;
39. while (1)
40. {
41. cout<<"\n-------------"<<endl;
42. cout<<"Operations on Stack"<<endl;
43. cout<<"\n-------------"<<endl;
44. cout<<"1.Push Element into the Stack"<<endl;
45. cout<<"2.Pop Element from the Stack"<<endl;
46. cout<<"3.Traverse the Stack"<<endl;
47. cout<<"4.Quit"<<endl;
48. cout<<"Enter your Choice: ";
10
49. cin>>choice;
50. switch(choice)
51. {
52. case 1:
53. cout<<"Enter value to be pushed into the stack: ";
54. cin>>item;
55. top = sl.push(top, item);
56. break;
57. case 2:
58. top = sl.pop(top);
59. break;
60. case 3:
61. sl.traverse(top);
62. break;
63. case 4:
64. exit(1);
65. break;
66. default:
67. cout<<"Wrong Choice"<<endl;
68. }
69. }
70. return 0;
71. }
72.
73. /*
74. * Push Element into the Stack
75. */
76. node *stack_list::push(node *top, int item)
77. {
78. node *tmp;
79. tmp = new (struct node);
80. tmp->info = item;
81. tmp->link = top;
82. top = tmp;
83. return top;
84. }
85.
86. /*
87. * Pop Element from the Stack
88. */
89. node *stack_list::pop(node *top)
90. {
91. node *tmp;
92. if (top == NULL)
93. cout<<"Stack is Empty"<<endl;
11
94. else
95. {
96. tmp = top;
97. cout<<"Element Popped: "<<tmp->info<<endl;
98. top = top->link;
99. delete(tmp);
100. }
101. return top;
102. }
103.
104. /*
105. * Traversing the Stack
106. */
107. void stack_list::traverse(node *top)
108. {
109. node *ptr;
110. ptr = top;
111. if (top == NULL)
112. cout<<"Stack is empty"<<endl;
113. else
114. {
115. cout<<"Stack elements :"<<endl;
116. while (ptr != NULL)
117. {
118. cout<<ptr->info<<endl;
119. ptr = ptr->link;
120. }
121. }
122. }

C++ Program to Implement Hash Tables


This C++ Program demonstrates operations on Hash Tables
Here is source code of the C++ Program to demonstrate Hash Tables.
1. /*
2. *C++ Program to Implement Hash Tables
3. */
4. #include<iostream>
5. #include<cstdlib>
6. #include<string>
7. #include<cstdio>
8. using namespace std;
9. const int TABLE_SIZE = 128;
10.
11. /*
12. * HashEntry Class Declaration
12
13. */
14. class HashEntry
15. {
16. public:
17. int key;
18. int value;
19. HashEntry(int key, int value)
20. {
21. this->key = key;
22. this->value = value;
23. }
24. };
25.
26. /*
27. * HashMap Class Declaration
28. */
29. class HashMap
30. {
31. private:
32. HashEntry **table;
33. public:
34. HashMap()
35. {
36. table = new HashEntry * [TABLE_SIZE];
37. for (int i = 0; i< TABLE_SIZE; i++)
38. {
39. table[i] = NULL;
40. }
41. }
42. /*
43. * Hash Function
44. */
45. int HashFunc(int key)
46. {
47. return key % TABLE_SIZE;
48. }
49. /*
50. * Insert Element at a key
51. */
52. void Insert(int key, int value)
53. {
54. int hash = HashFunc(key);
55. while (table[hash] != NULL && table[hash]->key != key)
56. {
57. hash = HashFunc(hash + 1);
13
58. }
59. if (table[hash] != NULL)
60. delete table[hash];
61. table[hash] = new HashEntry(key, value);
62. }
63. /*
64. * Search Element at a key
65. */
66. int Search(int key)
67. {
68. int hash = HashFunc(key);
69. while (table[hash] != NULL && table[hash]->key != key)
70. {
71. hash = HashFunc(hash + 1);
72. }
73. if (table[hash] == NULL)
74. return -1;
75. else
76. return table[hash]->value;
77. }
78.
79. /*
80. * Remove Element at a key
81. */
82. void Remove(int key)
83. {
84. int hash = HashFunc(key);
85. while (table[hash] != NULL)
86. {
87. if (table[hash]->key == key)
88. break;
89. hash = HashFunc(hash + 1);
90. }
91. if (table[hash] == NULL)
92. {
93. cout<<"No Element found at key "<<key<<endl;
94. return;
95. }
96. else
97. {
98. delete table[hash];
99. }
100. cout<<"Element Deleted"<<endl;
101. }
102. ~HashMap()
14
103. {
104. for (int i = 0; i < TABLE_SIZE; i++)
105. {
106. if (table[i] != NULL)
107. delete table[i];
108. delete[] table;
109. }
110. }
111. };
112. /*
113. * Main Contains Menu
114. */
115. int main()
116. {
117. HashMap hash;
118. int key, value;
119. int choice;
120. while (1)
121. {
122. cout<<"\n----------------------"<<endl;
123. cout<<"Operations on Hash Table"<<endl;
124. cout<<"\n----------------------"<<endl;
125. cout<<"1.Insert element into the table"<<endl;
126. cout<<"2.Search element from the key"<<endl;
127. cout<<"3.Delete element at a key"<<endl;
128. cout<<"4.Exit"<<endl;
129. cout<<"Enter your choice: ";
130. cin>>choice;
131. switch(choice)
132. {
133. case 1:
134. cout<<"Enter element to be inserted: ";
135. cin>>value;
136. cout<<"Enter key at which element to be inserted: ";
137. cin>>key;
138. hash.Insert(key, value);
139. break;
140. case 2:
141. cout<<"Enter key of the element to be searched: ";
142. cin>>key;
143. if (hash.Search(key) == -1)
144. {
145. cout<<"No element found at key "<<key<<endl;
146. continue;
147. }
15
148. else
149. {
150. cout<<"Element at key "<<key<<" : ";
151. cout<<hash.Search(key)<<endl;
152. }
153. break;
154. case 3:
155. cout<<"Enter key of the element to be deleted: ";
156. cin>>key;
157. hash.Remove(key);
158. break;
159. case 4:
160. exit(1);
161. default:
162. cout<<"\nEnter correct option\n";
163. }
164. }
165. return 0;
166. }

C++ Program to Implement Heap


This C++ Program demonstrates the implementation of Heap.
Here is source code of the C++ Program to demonstrate Heap.
1. /*
2. * C++ Program to Implement Heap
3. */
4. #include <iostream>
5. #include <cstdlib>
6. #include <vector>
7. #include <iterator>
8. using namespace std;
9. /*
10. * Class Declaration
11. */
12. class Heap
13. {
14. private:
15. vector <int> heap;
16. int left(int parent);
17. int right(int parent);
18. int parent(int child);
19. void heapifyup(int index);
20. void heapifydown(int index);
21. public:
22. Heap()
16
23. {}
24. void Insert(int element);
25. void DeleteMin();
26. int ExtractMin();
27. void DisplayHeap();
28. int Size();
29. };
30. /*
31. * Return Heap Size
32. */
33. int Heap::Size()
34. {
35. return heap.size();
36. }
37.
38. /*
39. * Insert Element into a Heap
40. */
41. void Heap::Insert(int element)
42. {
43. heap.push_back(element);
44. heapifyup(heap.size() -1);
45. }
46. /*
47. * Delete Minimum Element
48. */
49. void Heap::DeleteMin()
50. {
51. if (heap.size() == 0)
52. {
53. cout<<"Heap is Empty"<<endl;
54. return;
55. }
56. heap[0] = heap.at(heap.size() - 1);
57. heap.pop_back();
58. heapifydown(0);
59. cout<<"Element Deleted"<<endl;
60. }
61.
62. /*
63. * Extract Minimum Element
64. */
65. int Heap::ExtractMin()
66. {
67. if (heap.size() == 0)
17
68. {
69. return -1;
70. }
71. else
72. return heap.front();
73. }
74.
75. /*
76. * Display Heap
77. */
78. void Heap::DisplayHeap()
79. {
80. vector <int>::iterator pos = heap.begin();
81. cout<<"Heap --> ";
82. while (pos != heap.end())
83. {
84. cout<<*pos<<" ";
85. pos++;
86. }
87. cout<<endl;
88. }
89.
90. /*
91. * Return Left Child
92. */
93. int Heap::left(int parent)
94. {
95. int l = 2 * parent + 1;
96. if(l < heap.size())
97. return l;
98. else
99. return -1;
100. }
101.
102. /*
103. * Return Right Child
104. */
105. int Heap::right(int parent)
106. {
107. int r = 2 * parent + 2;
108. if(r < heap.size())
109. return r;
110. else
111. return -1;
112. }
18
113.
114. /*
115. * Return Parent
116. */
117. int Heap::parent(int child)
118. {
119. int p = (child - 1)/2;
120. if(child == 0)
121. return -1;
122. else
123. return p;
124. }
125.
126. /*
127. * Heapify- Maintain Heap Structure bottom up
128. */
129. void Heap::heapifyup(int in)
130. {
131. if (in >= 0 && parent(in) >= 0 && heap[parent(in)] > heap[in])
132. {
133. int temp = heap[in];
134. heap[in] = heap[parent(in)];
135. heap[parent(in)] = temp;
136. heapifyup(parent(in));
137. }
138. }
139.
140. /*
141. * Heapify- Maintain Heap Structure top down
142. */
143. void Heap::heapifydown(int in)
144. {
145.
146. int child = left(in);
147. int child1 = right(in);
148. if (child >= 0 && child1 >= 0 && heap[child] > heap[child1])
149. {
150. child = child1;
151. }
152. if (child > 0)
153. {
154. int temp = heap[in];
155. heap[in] = heap[child];
156. heap[child] = temp;
157. heapifydown(child);
19
158. }
159. }
160.
161. /*
162. * Main Contains Menu
163. */
164. int main()
165. {
166. Heap h;
167. while (1)
168. {
169. cout<<"------------------"<<endl;
170. cout<<"Operations on Heap"<<endl;
171. cout<<"------------------"<<endl;
172. cout<<"1.Insert Element"<<endl;
173. cout<<"2.Delete Minimum Element"<<endl;
174. cout<<"3.Extract Minimum Element"<<endl;
175. cout<<"4.Print Heap"<<endl;
176. cout<<"5.Exit"<<endl;
177. int choice, element;
178. cout<<"Enter your choice: ";
179. cin>>choice;
180. switch(choice)
181. {
182. case 1:
183. cout<<"Enter the element to be inserted: ";
184. cin>>element;
185. h.Insert(element);
186. break;
187. case 2:
188. h.DeleteMin();
189. break;
190. case 3:
191. cout<<"Minimum Element: ";
192. if (h.ExtractMin() == -1)
193. {
194. cout<<"Heap is Empty"<<endl;
195. }
196. else
197. cout<<"Minimum Element: "<<h.ExtractMin()<<endl;
198. break;
199. case 4:
200. cout<<"Displaying elements of Hwap: ";
201. h.DisplayHeap();
202. break;
20
203. case 5:
204. exit(1);
205. default:
206. cout<<"Enter Correct Choice"<<endl;
207. }
208. }
209. return 0;
210. }

C++ Program to Implement Queue using Linked List


This C++ program, using iteration, implements the list of elements removed from the queue in first
in first out mode using a linked list. Here is the source code of the C program to display the list of
elements removed from the queue.
1. /*
2. * C++ Program to Implement Queue using Linked List
3. */
4. #include<iostream>
5. #include<stdio.h>
6. #include<conio.h>
7. using namespace std;
8. struct node
9. {
10. int data;
11. node *next;
12. }*front = NULL,*rear = NULL,*p = NULL,*np = NULL;
13. void push(int x)
14. {
15. np = new node;
16. np->data = x;
17. np->next = NULL;
18. if(front == NULL)
19. {
20. front = rear = np;
21. rear->next = NULL;
22. }
23. else
24. {
25. rear->next = np;
26. rear = np;
27. rear->next = NULL;
28. }
29. }
30. int remove()
31. {
32. int x;
21
33. if(front == NULL)
34. {
35. cout<<"empty queue\n";
36. }
37. else
38. {
39. p = front;
40. x = p->data;
41. front = front->next;
42. delete(p);
43. return(x);
44. }
45. }
46. int main()
47. {
48. int n,c = 0,x;
49. cout<<"Enter the number of values to be pushed into queue\n";
50. cin>>n;
51. while (c < n)
52. {
53. cout<<"Enter the value to be entered into queue\n";
54. cin>>x;
55. push(x);
56. c++;
57. }
58. cout<<"\n\nRemoved Values\n\n";
59. while(true)
60. {
61. if (front != NULL)
62. cout<<remove()<<endl;
63. else
64. break;
65. }
66. getch();
67. }

C++ Program to Implement Hash Tables


This C++ Program demonstrates operations on Hash Tables
Here is source code of the C++ Program to demonstrate Hash Tables.
1. /*
2. *C++ Program to Implement Hash Tables
3. */
4. #include<iostream>
5. #include<cstdlib>
6. #include<string>
22
7. #include<cstdio>
8. using namespace std;
9. const int TABLE_SIZE = 128;
10.
11. /*
12. * HashEntry Class Declaration
13. */
14. class HashEntry
15. {
16. public:
17. int key;
18. int value;
19. HashEntry(int key, int value)
20. {
21. this->key = key;
22. this->value = value;
23. }
24. };
25.
26. /*
27. * HashMap Class Declaration
28. */
29. class HashMap
30. {
31. private:
32. HashEntry **table;
33. public:
34. HashMap()
35. {
36. table = new HashEntry * [TABLE_SIZE];
37. for (int i = 0; i< TABLE_SIZE; i++)
38. {
39. table[i] = NULL;
40. }
41. }
42. /*
43. * Hash Function
44. */
45. int HashFunc(int key)
46. {
47. return key % TABLE_SIZE;
48. }
49. /*
50. * Insert Element at a key
51. */
23
52. void Insert(int key, int value)
53. {
54. int hash = HashFunc(key);
55. while (table[hash] != NULL && table[hash]->key != key)
56. {
57. hash = HashFunc(hash + 1);
58. }
59. if (table[hash] != NULL)
60. delete table[hash];
61. table[hash] = new HashEntry(key, value);
62. }
63. /*
64. * Search Element at a key
65. */
66. int Search(int key)
67. {
68. int hash = HashFunc(key);
69. while (table[hash] != NULL && table[hash]->key != key)
70. {
71. hash = HashFunc(hash + 1);
72. }
73. if (table[hash] == NULL)
74. return -1;
75. else
76. return table[hash]->value;
77. }
78.
79. /*
80. * Remove Element at a key
81. */
82. void Remove(int key)
83. {
84. int hash = HashFunc(key);
85. while (table[hash] != NULL)
86. {
87. if (table[hash]->key == key)
88. break;
89. hash = HashFunc(hash + 1);
90. }
91. if (table[hash] == NULL)
92. {
93. cout<<"No Element found at key "<<key<<endl;
94. return;
95. }
96. else
24
97. {
98. delete table[hash];
99. }
100. cout<<"Element Deleted"<<endl;
101. }
102. ~HashMap()
103. {
104. for (int i = 0; i < TABLE_SIZE; i++)
105. {
106. if (table[i] != NULL)
107. delete table[i];
108. delete[] table;
109. }
110. }
111. };
112. /*
113. * Main Contains Menu
114. */
115. int main()
116. {
117. HashMap hash;
118. int key, value;
119. int choice;
120. while (1)
121. {
122. cout<<"\n----------------------"<<endl;
123. cout<<"Operations on Hash Table"<<endl;
124. cout<<"\n----------------------"<<endl;
125. cout<<"1.Insert element into the table"<<endl;
126. cout<<"2.Search element from the key"<<endl;
127. cout<<"3.Delete element at a key"<<endl;
128. cout<<"4.Exit"<<endl;
129. cout<<"Enter your choice: ";
130. cin>>choice;
131. switch(choice)
132. {
133. case 1:
134. cout<<"Enter element to be inserted: ";
135. cin>>value;
136. cout<<"Enter key at which element to be inserted: ";
137. cin>>key;
138. hash.Insert(key, value);
139. break;
140. case 2:
141. cout<<"Enter key of the element to be searched: ";
25
142. cin>>key;
143. if (hash.Search(key) == -1)
144. {
145. cout<<"No element found at key "<<key<<endl;
146. continue;
147. }
148. else
149. {
150. cout<<"Element at key "<<key<<" : ";
151. cout<<hash.Search(key)<<endl;
152. }
153. break;
154. case 3:
155. cout<<"Enter key of the element to be deleted: ";
156. cin>>key;
157. hash.Remove(key);
158. break;
159. case 4:
160. exit(1);
161. default:
162. cout<<"\nEnter correct option\n";
163. }
164. }
165. return 0;
166. }

ALGORITHM
Algorithm is a step by step procedure, which defines a set of instructions to be executed in certain
order to get the desired output.

ALGORITHM ANALYSIS
A problem can be solved in more than one ways. Therefore, many solution algorithms can be
derived for a given problem. We analyze available algorithms to find and implement the best
suitable algorithm.

Criteria of Algorithm Analysis


An algorithm are generally analyzed on two factors − time and space. That is, how
much execution time and how much extra space required by the algorithm.
What is asymptotic analysis of an algorithm?
Asymptotic analysis of an algorithm, refers to defining the mathematical boundation/framing of
its run-time performance. Using asymptotic analysis, we can very well conclude the best case,
average case and worst case scenario of an algorithm.
What are asymptotic notations?
Asymptotic analysis can provide three levels of mathematical binding of execution time of an
algorithm −
26
 Best case is represented by Ω(n) notation.
 Worst case is represented by Ο(n) notation.
 Average case is represented by Θ(n) notation.

Approaches to develop Algorithms


There are three commonly used approaches to develop algorithms −
 Greedy Approach − finding solution by choosing next best option
 Divide and Conquer − dividing the problem to a minimum possible sub-problem and
solving them independently
 Dynamic Programming − dividing the problem to a minimum possible sub-problem and
solving them combined
Some examples greedy algorithms.
The below given problems find their solution using greedy algorithm approach −
 Travelling Salesman Problem
 Prim's Minimal Spanning Tree Algorithm
 Kruskal's Minimal Spanning Tree Algorithm
 Djikstral’s Minimal Spanning Tree Algorithm
 Graph - Map Coloring
 Graph - Vertex Cover
 Knapsack Problem
 Job Scheduling Problem
Some examples of divide and conquer algorithms
The below given problems find their solution using divide and conquer algorithm approach −
 Merge Sort
 Quick Sort
 Binary Search
 Strassen's Matrix Multiplication
 Closest pair (points)
Some examples of dynamic programming algorithms
The below given problems find their solution using divide and conquer algorithm approach −
 Fibonacci number series
 Knapsack problem
 Tower of Hanoi
 All pair shortest path by Floyd-Warshall
 Shortest path by Dijkstra
 Project scheduling
Linear searching
Linear search tries to find an item in a sequentially arranged data type. These sequentially arranged
data items known as array or list, are accessible in incrementing memory location. Linear search
compares expected data item with each of data items in list or array. The average case time
complexity of linear search is Ο(n) and worst case complexity is Ο(n2). Data in target arrays/lists
need not to be sorted.

Binary Search

27
A binary search works only on sorted lists or arrays. This search selects from the middle which
splits the entire list into two parts. First the middle is compared.
This search first compares the target value to the mid of the list. If it is not found, then it takes
decision on whether.
BUBBLE SORT
Bubble sort is comparison based algorithm in which each pair of adjacent elements is compared
and elements are swapped if they are not in order. Because the time complexity is Ο(n2), it is not
suitable for large set of data.
INSERTION SORT
Insertion sort divides the list into two sub-list, sorted and unsorted. It takes one element at a time
and finds its appropriate location in sorted sub-list and insert there. The output after insertion is a
sorted sub-list. It iteratively works on all the elements of unsorted sub-list and inserts them to
sorted sub-list in order.

SELECTION SORT
Selection sort is in-place sorting technique. It divides the data set into two sub-lists: sorted and
unsorted. Then it selects the minimum element from unsorted sub-list and places it into the sorted
list. This iterates unless all the elements from unsorted sub-list are consumed into sorted sub-list.

Difference between Insertion sort and Selection sort


Both sorting techniques maintains two sub-lists, sorted and unsorted and both take one element at
a time and places it into sorted sub-list. Insertion sort works on the current element in hand and
places it in the sorted array at appropriate location maintaining the properties of insertion sort.
Whereas, selection sort searches the minimum from the unsorted sub-list and replaces it with the
current element in hand.

MERGE SORT
Merge sort is sorting algorithm based on divide and conquer programming approach. It keeps on
dividing the list into smaller sub-list until all sub-list has only 1 element. Then it merges them in
a sorted way until all sub-lists are consumed. It has run-time complexity of Ο(n log n) and it needs
Ο(n) auxiliary space.

SHELL SORT
Shell sort can be said to be a variant of insertion sort. Shell sort divides the list into smaller sublist
based on some gap variable and then each sub-list is sorted using insertion sort. In best cases, it
can perform up to Ο(n log n).

QUICK SORT
Quick sort uses divide and conquer approach. It divides the list in smaller 'partitions' using 'pivot'.
The values which are smaller than the pivot are arranged in the left partition and greater values are
arranged in the right partition. Each partition is recursively sorted using quick sort.

Kruskal's algorithm

28
This algorithm treats the graph as a forest and every node it as an individual tree. A tree connects
to another only and only if it has least cost among all available options and does not violate
minimum spanning tree MST properties.

Prim's algorithm
Prim's algorithm treats the nodes as a single tree and keeps on adding new nodes to the spanning
tree from the given graph.

GRAPH
A graph is a pictorial representation of a set of objects where some pairs of objects are connected
by links. The interconnected objects are represented by points termed as vertices, and the links that
connect the vertices are called edges.

TREE
A tree is a minimally connected graph having no loops and circuits.

SPANNING TREE
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible
number of edges. A spanning tree does not have cycles and it cannot be disconnected.
How many spanning trees can a graph has?
It depends on how connected the graph is. A complete undirected graph can have maximum nn-1
number of spanning trees, where n is number of nodes.

BINARY TREE
A binary tree has a special condition that each node can have two children at maximum.

BINARY SEARCH TREE


A binary search tree is a binary tree with a special provision where a node's left child must have
value less than its parent's value and node's right child must have value greater than its parent
value.
Interpolation search technique
Interpolation search is an improved variant of binary search. This search algorithm works on the
probing position of required value.

MINIMUM SPANNING TREE (MST)


In a weighted graph, a minimum spanning tree is a spanning tree that has minimum weight that all
other spanning trees of the same graph.

Depth First Search


Depth First Search algorithm(DFS) traverses a graph in a depth ward motion and uses a stack to
remember to get the next vertex to start a search when a dead end occurs in any iteration.

Breadth First Search


Breadth First Search algorithm(BFS) traverses a graph in a breadth wards motion and uses a queue
to remember to get the next vertex to start a search when a dead end occurs in any iteration.
29
TREE TRAVERSAL
Tree traversal is a process to visit all the nodes of a tree. Because, all nodes are connected via
edges (links) we always start from the root (head) node. There are three ways which we use to
traverse a tree −
 In-order Traversal
 Pre-order Traversal
 Post-order Traversal

HEAP DATA STRUCTURE


Heap is a special balanced binary tree data structure where root-node key is compared with its
children and arranged accordingly. A min-heap, a parent node has key value less than its child
does and a max-heap parent node has value greater than its child does.

RECURSIVE FUNCTION
A recursive function is one, which calls itself, directly or calls a function that in turn calls it. Every
recursive function follows the recursive properties − base criteria where functions stops calling
itself and progressive approach where the functions tries to meet the base criteria in each iteration.

TOWER of HANOI
Tower of Hanoi is a mathematical puzzle, which consists of three tower (pegs) and more than one
rings. All rings are of different size and stacked upon each other where the large disk is always
below the small disk. The aim is to move the tower of disk from one peg to another, without
breaking its properties.

HASHING
Hashing is a technique to convert a range of key values into a range of indexes of an array. By
using hash tables, we can create an associative data storage where data index can be find by
providing its key values.

Similarities between References and Pointers


 Both references and pointers can be used to change local variables of one function inside
another function.
 Both of them can also be used to save copying of big objects when passed as arguments to
functions or returned from functions, to get efficiency gain.

Differences between References and Pointers


Despite above similarities, there are following differences between references and pointers.
References are less powerful than pointers
1) Once a reference is created, it cannot be later made to reference another object; it cannot be
reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers

30
Due to the above limitations, references in C++ cannot be used for implementing data structures
like Linked List, Tree, etc. In Java, references do not have above restrictions, and can be used to
implement all data structures. References being more powerful in Java is the main reason Java
does not need pointers.
References are safer and easier to use:
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to
exist. It is still possible to have references that do not refer to a valid location
2) Easier to use: References do not need dereferencing operator to access the value. They can be
used like normal variables. ‘&’ operator is needed only at the time of declaration. In addition,
members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow
operator (->) is needed to access members.

31

You might also like