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

Data Structure Java

The document discusses different types of data structures including linear and non-linear data structures. Linear data structures include arrays, linked lists, stacks, and queues. Non-linear data structures include trees and graphs. Common operations on stacks like push, pop, and peek are also explained.

Uploaded by

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

Data Structure Java

The document discusses different types of data structures including linear and non-linear data structures. Linear data structures include arrays, linked lists, stacks, and queues. Non-linear data structures include trees and graphs. Common operations on stacks like push, pop, and peek are also explained.

Uploaded by

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

In computer science, a 

data structure is a data organization, management, and storage format that


enables efficient access and modification. More precisely, a data structure is a collection
of data values, the relationships among them, and the functions or operations that can be applied to
the data.

A data structure is a way of organizing the data. So we can classify data structures as


shown into primitive or standard data structures and non-primitive or user-defined data
structures. ... These user-defined data structures are further classified into linear and non-
linear data structures.

Types of Data Structure

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.

Types of Linear Data Structures are given below:

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

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

The individual elements of the array age are:

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

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

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

A stack is an abstract data type (ADT), can be implemented in most of the programming
languages. It is named as stack because it behaves like a real-world stack, for example: -
piles of plates or deck of cards etc. 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.

Types of Non Linear Data Structures are given below:

Trees: Trees are multilevel data structures with a hierarchical relationship among its
elements known as nodes. The bottommost nodes in the 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.

Graphs: It is not in ISC syllabus


Stack
1. Stack is an ordered list in which, insertion and deletion can be performed only at one
end that is called top.
2. Stack is a recursive data structure having pointer to its top element.
3. Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element which
is inserted first in the stack, will be deleted last from the stack.

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.

1. Push : Adding an element onto the stack


2. Pop : Removing an element from the stack

3. Peek : Look all the elements of stack without removing them.

How the stack grows?


Scenario 1 : Stack is empty

The stack is called empty if it doesn't contain any element inside it. At this stage, the value
of variable top is -1.

Scenario 2 : Stack is not empty

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.

In the following stack, after deleting 10 from the stack, top = 1.


Top and its value :

Top position Status of stack

-1 Empty

0 Only one element in the stack

N-1 Stack is full

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.

Adding an element onto the stack (push operation)


Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.

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   

Time Complexity : o(1)

implementation of push algorithm


1. void push (int val,int n) //n is size of the stack   
2. {  
3.     if (top == n )   
4.    System.out.print("\n Overflow");   
5.     else   
6.     {  
7.     top = top +1;   
8.     stack[top] = val;   
9.     }   
10. }   
Deletion of an element from a stack (Pop operation)
Deletion of an element from the top of the stack is called pop operation. The value of the
variable top will be incremented by 1 whenever an item is deleted from the stack. The top
most element of the stack is stored in an another variable and then the top is decremented
by 1. the operation returns the deleted value that was stored in another variable as the
result.

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;    

Time Complexity : O(1)

Implementation of POP algorithm


int pop ()  
1. {   
2.     if(top == -1)   
3.     {  
4.         System.out.print ("Underflow");  
5.         return 0;  
6.     }  
7.     else  
8.     {  
9.         return stack[top - - ];   
10.     }    
11. }   
Visiting each element of the stack (Peek operation)
Peek operation involves returning the element which is present at the top of the stack
without deleting it. Underflow condition can occur if we try to return the top element in an
already empty stack.

Algorithm :

PEEK (STACK, TOP)

1. Begin   
2.     if top = -1 then stack empty    
3.     item = stack[top]   
4.     return item  
5. End    

Time complexity: o(n)

Implementation of Peek algorithm


1. int peek()  
2. {  
3.     if (top == -1)   
4.     {  
5.         System.out.print ("Underflow");  
6.         return 0;   
7.     }  
8.     else  
9.     {  
10.         return stack [top];  
11.     }  
12. }  
Java Program

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.

2. Queue is referred to be as First In First Out list.

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

ordering of actions. There are various applications of queues discussed as below.

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

songs from the play-list.


5. Queues are used in operating systems for handling interrupts.

Complexity

Data Structure Time Complexity

Average Worst

Access Search Insertion Deletion Access Search Insertion Deletion

Queue θ(n) θ(n) θ(1) θ(1) O(n) O(n) O(1) O(1)

next →← prev

Array representation of Queue


We can easily represent queue by using linear arrays. There are two variables i.e. front
and rear, that are implemented in the case of every queue. Front and rear variables point
to the position from where insertions and deletions are performed in a queue. Initially,
the value of front and queue is -1 which represents an empty queue. Array
representation of a queue containing 5 elements along with the respective values of front
and rear, is shown in the following figure.
The above figure shows the queue of characters forming the English word "HELLO".
Since, No deletion is performed in the queue till now, therefore the value of front remains
-1 . However, the value of rear increases by one every time an insertion is performed in
the queue. After inserting an element into the queue shown in the above figure, the
queue will look something like following. The value of rear will become 5 while the value
of front remains same.

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. }  

Algorithm to delete an element from the queue


If, the value of front is -1 or value of front is greater than rear , write an underflow
message and exit.

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. }   

Menu driven program to implement queue using array


1. #include<stdio.h>   
2. #include<stdlib.h>  
3. #define maxsize 5  
4. void insert();  
5. void delete();  
6. void display();  
7. int front = -1, rear = -1;  
8. int queue[maxsize];  
9. void main ()  
10. {  
11.     int choice;   
12.     while(choice != 4)   
13.     {     
14.         printf("\n*************************Main Menu*************************
****\n");  
15.         printf("\
n======================================================
===========\n");  
16.         printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\
n");  
17.         printf("\nEnter your choice ?");  
18.         scanf("%d",&choice);  
19.         switch(choice)  
20.         {  
21.             case 1:  
22.             insert();  
23.             break;  
24.             case 2:  
25.             delete();  
26.             break;  
27.             case 3:  
28.             display();  
29.             break;  
30.             case 4:  
31.             exit(0);  
32.             break;  
33.             default:   
34.             printf("\nEnter valid choice??\n");  
35.         }  
36.     }  
37. }  
38. void insert()  
39. {  
40.     int item;  
41.     printf("\nEnter the element\n");  
42.     scanf("\n%d",&item);      
43.     if(rear == maxsize-1)  
44.     {  
45.         printf("\nOVERFLOW\n");  
46.         return;  
47.     }  
48.     if(front == -1 && rear == -1)  
49.     {  
50.         front = 0;  
51.         rear = 0;  
52.     }  
53.     else   
54.     {  
55.         rear = rear+1;  
56.     }  
57.     queue[rear] = item;  
58.     printf("\nValue inserted ");  
59.       
60. }  
61. void delete()  
62. {  
63.     int item;   
64.     if (front == -1 || front > rear)  
65.     {  
66.         printf("\nUNDERFLOW\n");  
67.         return;  
68.               
69.     }  
70.     else  
71.     {  
72.         item = queue[front];  
73.         if(front == rear)  
74.         {  
75.             front = -1;  
76.             rear = -1 ;  
77.         }  
78.         else   
79.         {  
80.             front = front + 1;  
81.         }  
82.         printf("\nvalue deleted ");  
83.     }  
84.       
85.       
86. }  
87.       
88. void display()  
89. {  
90.     int i;  
91.     if(rear == -1)  
92.     {  
93.         printf("\nEmpty queue\n");  
94.     }  
95.     else  
96.     {   printf("\nprinting values .....\n");  
97.         for(i=front;i<=rear;i++)  
98.         {  
99.             printf("\n%d\n",queue[i]);  
100.         }     
101.     }  
102. }  

Output:

*************Main Menu**************

==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?1

Enter the element


123

Value inserted

*************Main Menu**************

==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?1

Enter the element


90

Value inserted

*************Main Menu**************

===================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?2

value deleted

*************Main Menu**************
==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?3

printing values .....

90

*************Main Menu**************
==============================================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?4

Drawback of array implementation


Although, the technique of creating a queue is easy, but there are some drawbacks of
using this technique to implement a queue.

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).

o Deciding the array size


On of the most common problem with array implementation is the size of the array which
requires to be declared in advance. Due to the fact that, the queue can be extended at
runtime depending upon the problem, the extension in the array size is a time taking
process and almost impossible to be performed at runtime since a lot of reallocations take
place. Due to this reason, we can declare the array large enough so that we can store queue
elements as enough as possible but the main problem with this declaration is that, most of
the array slots (nearly half) can never be reused. It will again lead to memory wastage.

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. }  

You might also like