Data Structure Java
Data Structure Java
A data structure is a collection of data type 'values' which are stored and organized in such a
way that it allows for efficient access and modification. ... When we think of data structures,
there are generally four forms: Linear: arrays, lists. Tree: binary, heaps, space partitioning etc.
There are two fundamental kinds of data structures: array of contiguous memory locations
and linked structures.
next →← prev
Data Structure
Introduction
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 vitle 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
Data Structure Classification
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.
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.
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. it follows Last-In-First-Out (LIFO) methodology for
storing the data items.
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.
Trees: Trees are multilevel data structures with a hierarchical relationship among its
elements known as nodes. The bottommost nodes in the herierchy 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 children except the leaf nodes whereas each node
can have atmost one parent except the root node. Trees can be classfied into many
categories like Binary Tree.
Applications of Stack
1. Recursion
2. Expression evaluations and conversions
3. Parsing
4. Browsers
5. Editors
6. Tree Traversals
Operations on Stack
There are various operations which can be performed on stack.
The stack is called empty if it doesn't contain any element inside it. At this stage, the value
of variable top is -1.
Value of top will get increased by 1 every time when we add any element to the stack. In
the following stack, After adding first element, top = 2.
Scenario 3 : Deletion of an element
Value of top will get decreased by 1 whenever an element is deleted from the stack.
-1 Empty
N Overflow
Array implementation of Stack
In array implementation, the stack is formed by using the array. All the operations
regarding the stack are performed using arrays. Lets see how each operation can be
implemented on the stack using array data structure.
1. Increment the variable Top so that it can now refere to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new
element at the top of the stack.
Stack is overflown when we try to insert an element into a completely filled stack therefore,
our main function must always avoid stack overflow condition.
Algorithm:
1. begin
2. if top = n then stack full
3. top = top + 1
4. stack (top) : = item;
5. end
The underflow condition occurs when we try to delete an element from an already empty
stack.
Algorithm :
1. begin
2. if top = 0 then stack empty;
3. item := stack(top);
4. top = top - 1;
5. end;
Algorithm :
1. Begin
2. if top = -1 then stack empty
3. item = stack[top]
4. return item
5. End
1. import java.util.Scanner;
2. class Stack
3. {
4. int top;
5. int maxsize = 10;
6. int[] arr = new int[maxsize];
7.
8.
9. boolean isEmpty()
10. {
11. return (top < 0);
12. }
13. Stack()
14. {
15. top = -1;
16. }
17. boolean push (Scanner sc)
18. {
19. if(top == maxsize-1)
20. {
21. System.out.println("Overflow !!");
22. return false;
23. }
24. else
25. {
26. System.out.println("Enter Value");
27. int val = sc.nextInt();
28. top++;
29. arr[top]=val;
30. System.out.println("Item pushed");
31. return true;
32. }
33. }
34. boolean pop ()
35. {
36. if (top == -1)
37. {
38. System.out.println("Underflow !!");
39. return false;
40. }
41. else
42. {
43. top --;
44. System.out.println("Item popped");
45. return true;
46. }
47. }
48. void display ()
49. {
50. System.out.println("Printing stack elements .....");
51. for(int i = top; i>=0;i--)
52. {
53. System.out.println(arr[i]);
54. }
55. }
56. }
57. public class Stack_Operations {
58. public static void main(String[] args) {
59. int choice=0;
60. Scanner sc = new Scanner(System.in);
61. Stack s = new Stack();
62. System.out.println("*********Stack operations using array*********\n");
63. System.out.println("\n------------------------------------------------\n");
64. while(choice != 4)
65. {
66. System.out.println("\nChose one from the below options...\n");
67. System.out.println("\n1.Push\n2.Pop\n3.Show\n4.Exit");
68. System.out.println("\n Enter your choice \n");
69. choice = sc.nextInt();
70. switch(choice)
71. {
72. case 1:
73. {
74. s.push(sc);
75. break;
76. }
77. case 2:
78. {
79. s.pop();
80. break;
81. }
82. case 3:
83. {
84. s.display();
85. break;
86. }
87. case 4:
88. {
89. System.out.println("Exiting....");
90. System.exit(0);
91. break;
92. }
93. default:
94. {
95. System.out.println("Please Enter valid choice ");
96. }
97. };
98. }
99. }
100. }
next →← prev
Queue
1. A queue can be defined as an ordered list which enables insert operations to be performed
at one end called REAR and delete operations to be performed at another end called FRONT.
3. For example, people waiting in line for a rail ticket form a queue.
Applications of Queue
Due to the fact that queue performs actions on first in first out basis which is quite fair for the
1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
2. Queues are used in asynchronous transfer of data (where data is not being transferred at the
same rate between two processes) for eg. pipes, file IO, sockets.
3. Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
4. Queue are used to maintain the play list in media players in order to add and remove the
Complexity
Average Worst
next →← prev
After deleting an element, the value of front will increase from -1 to 0. however, the
queue will look something like following.
Algorithm to insert any element in a queue
Check if the queue is already full by comparing rear to max - 1. if so, then return an
overflow error.
If the item is to be inserted as the first element in the list, in that case set the value of
front and rear to 0 and insert the element at the rear end.
Otherwise keep increasing the value of rear and insert each element one by one having
rear as the index.
Algorithm
o Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step
[END OF IF]
o Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
o Step 3: Set QUEUE[REAR] = NUM
o Step 4: EXIT
C Function
1. void insert (int queue[], int max, int front, int rear, int item)
2. {
3. if (rear + 1 == max)
4. {
5. printf("overflow");
6. }
7. else
8. {
9. if(front == -1 && rear == -1)
10. {
11. front = 0;
12. rear = 0;
13. }
14. else
15. {
16. rear = rear + 1;
17. }
18. queue[rear]=item;
19. }
20. }
Otherwise, keep increasing the value of front and return the item stored at the front end
of the queue at each time.
Algorithm
o Step 1: IF FRONT = -1 or FRONT > REAR
Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
o Step 2: EXIT
C Function
1. int delete (int queue[], int max, int front, int rear)
2. {
3. int y;
4. if (front == -1 || front > rear)
5.
6. {
7. printf("underflow");
8. }
9. else
10. {
11. y = queue[front];
12. if(front == rear)
13. {
14. front = rear = -1;
15. else
16. front = front + 1;
17.
18. }
19. return y;
20. }
21. }
Output:
*************Main Menu**************
==============================================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Value inserted
*************Main Menu**************
==============================================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Value inserted
*************Main Menu**************
===================================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
value deleted
*************Main Menu**************
==============================================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
90
*************Main Menu**************
==============================================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
o Memory wastage : The space of the array, which is used to store queue
elements, can never be reused to store the elements of that queue because the
elements can only be inserted at front end and the value of front might be so high
so that, all the space before that, can never be filled.
The above figure shows how the memory space is wasted in the array representation of
queue. In the above figure, a queue of size 10 having 3 elements, is shown. The value of
the front variable is 5, therefore, we can not reinsert the values in the place of already
deleted element before the position of front. That much space of the array is wasted and
can not be used in the future (for this queue).
101. import java.util.Scanner;
102. class Stack
103. {
104. int top;
105. int maxsize = 10;
106. int[] arr = new int[maxsize];
107.
108.
109. boolean isEmpty()
110. {
111. return (top < 0);
112. }
113. Stack()
114. {
115. top = -1;
116. }
117. boolean push (Scanner sc)
118. {
119. if(top == maxsize-1)
120. {
121. System.out.println("Overflow !!");
122. return false;
123. }
124. else
125. {
126. System.out.println("Enter Value");
127. int val = sc.nextInt();
128. top++;
129. arr[top]=val;
130. System.out.println("Item pushed");
131. return true;
132. }
133. }
134. boolean pop ()
135. {
136. if (top == -1)
137. {
138. System.out.println("Underflow !!");
139. return false;
140. }
141. else
142. {
143. top --;
144. System.out.println("Item popped");
145. return true;
146. }
147. }
148. void display ()
149. {
150. System.out.println("Printing stack elements .....");
151. for(int i = top; i>=0;i--)
152. {
153. System.out.println(arr[i]);
154. }
155. }
156. }
157. public class Stack_Operations {
158. public static void main(String[] args) {
159. int choice=0;
160. Scanner sc = new Scanner(System.in);
161. Stack s = new Stack();
162. System.out.println("*********Stack operations using array*********\n");
163. System.out.println("\n------------------------------------------------\n");
164. while(choice != 4)
165. {
166. System.out.println("\nChose one from the below options...\n");
167. System.out.println("\n1.Push\n2.Pop\n3.Show\n4.Exit");
168. System.out.println("\n Enter your choice \n");
169. choice = sc.nextInt();
170. switch(choice)
171. {
172. case 1:
173. {
174. s.push(sc);
175. break;
176. }
177. case 2:
178. {
179. s.pop();
180. break;
181. }
182. case 3:
183. {
184. s.display();
185. break;
186. }
187. case 4:
188. {
189. System.out.println("Exiting....");
190. System.exit(0);
191. break;
192. }
193. default:
194. {
195. System.out.println("Please Enter valid choice ");
196. }
197. };
198. }
199. }
200. }
C# Program
201. import java.util.Scanner;
202. class Stack
203. {
204. int top;
205. int maxsize = 10;
206. int[] arr = new int[maxsize];
207.
208.
209. boolean isEmpty()
210. {
211. return (top < 0);
212. }
213. Stack()
214. {
215. top = -1;
216. }
217. boolean push (Scanner sc)
218. {
219. if(top == maxsize-1)
220. {
221. System.out.println("Overflow !!");
222. return false;
223. }
224. else
225. {
226. System.out.println("Enter Value");
227. int val = sc.nextInt();
228. top++;
229. arr[top]=val;
230. System.out.println("Item pushed");
231. return true;
232. }
233. }
234. boolean pop ()
235. {
236. if (top == -1)
237. {
238. System.out.println("Underflow !!");
239. return false;
240. }
241. else
242. {
243. top --;
244. System.out.println("Item popped");
245. return true;
246. }
247. }
248. void display ()
249. {
250. System.out.println("Printing stack elements .....");
251. for(int i = top; i>=0;i--)
252. {
253. System.out.println(arr[i]);
254. }
255. }
256. }
257. public class Stack_Operations {
258. public static void main(String[] args) {
259. int choice=0;
260. Scanner sc = new Scanner(System.in);
261. Stack s = new Stack();
262. System.out.println("*********Stack operations using array*********\n");
263. System.out.println("\n------------------------------------------------\n");
264. while(choice != 4)
265. {
266. System.out.println("\nChose one from the below options...\n");
267. System.out.println("\n1.Push\n2.Pop\n3.Show\n4.Exit");
268. System.out.println("\n Enter your choice \n");
269. choice = sc.nextInt();
270. switch(choice)
271. {
272. case 1:
273. {
274. s.push(sc);
275. break;
276. }
277. case 2:
278. {
279. s.pop();
280. break;
281. }
282. case 3:
283. {
284. s.display();
285. break;
286. }
287. case 4:
288. {
289. System.out.println("Exiting....");
290. System.exit(0);
291. break;
292. }
293. default:
294. {
295. System.out.println("Please Enter valid choice ");
296. }
297. };
298. }
299. }
300. }