Common operations on various Data Structures
Last Updated :
27 Mar, 2023
Data Structure is the way of storing data in computer's memory so that it can be used easily and efficiently. There are different data-structures used for the storage of data. It can also be defined as a mathematical or logical model of a particular organization of data items. The representation of particular data structure in the main memory of a computer is called as storage structure.
For Examples: Array, Stack, Queue, Tree, Graph, etc.
Operations on different Data Structure:
There are different types of operations that can be performed for the manipulation of data in every data structure. Some operations are explained and illustrated below:
- Traversing: Traversing a Data Structure means to visit the element stored in it. It visits data in a systematic manner. This can be done with any type of DS.
Below is the program to illustrate traversal in an array, stack, queue and linkedlist:
Array
// C++ program to traversal in an array
#include <iostream>
using namespace std;
// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// size of array
int N = sizeof(arr) / sizeof(arr[0]);
// Traverse the element of arr[]
for (int i = 0; i < N; i++) {
// Print the element
cout << arr[i] << ' ';
}
return 0;
}
Stack
// C++ program to traversal in an stack
#include <bits/stdc++.h>
using namespace std;
// Function to print the element in stack
void printStack(stack<int>& St)
{
// Traverse the stack
while (!St.empty()) {
// Print top element
cout << St.top() << ' ';
// Pop top element
St.pop();
}
}
// Driver Code
int main()
{
// Initialise stack
stack<int> St;
// Insert Element in stack
St.push(4);
St.push(3);
St.push(2);
St.push(1);
// Print elements in stack
printStack(St);
return 0;
}
Queue
// C++ program to traversal
// in an queue
#include <bits/stdc++.h>
using namespace std;
// Function to print the
// element in queue
void printQueue(queue<int>& Q)
{
// Traverse the stack
while (!Q.empty()) {
// Print top element
cout << Q.front() << ' ';
// Pop top element
Q.pop();
}
}
// Driver Code
int main()
{
// Initialise queue
queue<int> Q;
// Insert element
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
// Print elements
printQueue(Q);
return 0;
}
LinkedList
// C++ program to traverse the
// given linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
// Function that allocates a new
// node with given data
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// Function to insert a new node
// at the end of linked list
Node* insertEnd(Node* head, int data)
{
// If linked list is empty,
// Create a new node
if (head == NULL)
return newNode(data);
// If we have not reached the end
// Keep traversing recursively
else
head->next = insertEnd(head->next, data);
return head;
}
/// Function to traverse given LL
void traverse(Node* head)
{
if (head == NULL)
return;
// If head is not NULL,
// print current node and
// recur for remaining list
cout << head->data << " ";
traverse(head->next);
}
// Driver Code
int main()
{
// Given Linked List
Node* head = NULL;
head = insertEnd(head, 1);
head = insertEnd(head, 2);
head = insertEnd(head, 3);
head = insertEnd(head, 4);
// Function Call to traverse LL
traverse(head);
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Below is the program to illustrate traversal in an array:
C++
// C++ program to traversal in an array
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// size of array
int N = sizeof(arr)/sizeof(arr[0]);
// Traverse the element of arr[]
for (int i = 0; i < N; i++) {
// Print the element
cout << arr[i] << " ";
}
return 0;
}
// This code is contributed by jana_sayantan.
Java
// Java program to traversal in an array
import java.util.*;
class GFG{
// Driver Code
public static void main(String[] args)
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// size of array
int N = arr.length;
// Traverse the element of arr[]
for (int i = 0; i < N; i++) {
// Print the element
System.out.print(arr[i] + " ");
}
}
}
// This code contributed by Rajput-Ji
Python3
# Python program to traversal in an array
# Driver Code
if __name__ == '__main__':
# Initialise array
arr = [ 1, 2, 3, 4 ];
# size of array
N = len(arr);
# Traverse the element of arr
for i in range(N):
# Print element
print(arr[i], end=" ");
# This code is contributed by Rajput-Ji
C#
// C# program to traversal in an array
using System;
public class GFG {
// Driver Code
public static void Main(String[] args) {
// Initialise array
int []arr = { 1, 2, 3, 4 };
// size of array
int N = arr.Length;
// Traverse the element of []arr
for (int i = 0; i < N; i++) {
// Print the element
Console.Write(arr[i] + " ");
}
}
}
// This code contributed by Rajput-Ji
JavaScript
<script>
// javascript program to traversal in an array // Driver Code
// Initialise array
var arr = [ 1, 2, 3, 4 ];
// size of array
var N = arr.length;
// Traverse the element of arr
for (i = 0; i < N; i++) {
// Print the element
document.write(arr[i] + " ");
}
// This code is contributed by Rajput-Ji
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Below is the program to illustrate traversal in a Stack:
C++
#include <iostream>
#include <stack>
using namespace std;
// Function to print the element in stack
void printStack(stack<int> St){
// Traverse the stack
while (!St.empty()) {
// Print top element
cout << St.top() <<" ";
// Pop top element
St.pop();
}
}
int main() {
// Initialise stack
stack<int> St;
// Insert Element in stack
St.push(4);
St.push(3);
St.push(2);
St.push(1);
// Print elements in stack
printStack(St);
return 0;
}
// This code is contributed by lokesh.
Java
// Java program to traversal in an stack
import java.util.*;
class GFG{
// Function to print the element in stack
static void printStack(Stack<Integer> St)
{
// Traverse the stack
while (!St.isEmpty()) {
// Print top element
System.out.print(St.peek() +" ");
// Pop top element
St.pop();
}
}
// Driver Code
public static void main(String[] args)
{
// Initialise stack
Stack<Integer> St = new Stack<>() ;
// Insert Element in stack
St.add(4);
St.add(3);
St.add(2);
St.add(1);
// Print elements in stack
printStack(St);
}
}
// This code contributed by Rajput-Ji
Python3
# Function to print the element in stack
def print_stack(St):
# Traverse the stack
while St:
# Print top element
print(St.pop(), end=' ')
# Test function with sample input
St = []
St.append(4)
St.append(3)
St.append(2)
St.append(1)
print_stack(St)
# This code is contributed by Potta Lokesh
C#
// C# program to traversal in an stack
using System;
using System.Collections.Generic;
public class GFG {
// Function to print the element in stack
static void printStack(Stack<int> St) {
// Traverse the stack
while (St.Count != 0) {
// Print top element
Console.Write(St.Peek() + " ");
// Pop top element
St.Pop();
}
}
// Driver Code
public static void Main(String[] args)
{
// Initialise stack
Stack<int> St = new Stack<int>();
// Insert Element in stack
St.Push(4);
St.Push(3);
St.Push(2);
St.Push(1);
// Print elements in stack
printStack(St);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// javascript program to traversal in an stack
// Function to print the element in stack
function printStack(St)
{
// Traverse the stack
while (St.length != 0)
{
// Print top element
document.write(St.pop() + " ");
}
}
// Driver Code
// Initialise stack
var St = [];
// Insert Element in stack
St.push(4);
St.push(3);
St.push(2);
St.push(1);
// Print elements in stack
printStack(St);
// This code is contributed by Rajput-Ji
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
- Searching: Searching means to find a particular element in the given data-structure. It is considered as successful when the required element is found. Searching is the operation which we can performed on data-structures like array, linked-list, tree, graph, etc.
Below is the program to illustrate searching an element in an array, stack, queue and linkedlist:
Array
// C++ program to searching in an array
#include <iostream>
using namespace std;
// Function that finds element K in the
// array
void findElement(int arr[], int N, int K)
{
// Traverse the element of arr[]
// to find element K
for (int i = 0; i < N; i++) {
// If Element is present then
// print the index and return
if (arr[i] == K) {
cout << "Element found!";
return;
}
}
cout << "Element Not found!";
}
// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// Element to be found
int K = 3;
// size of array
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
findElement(arr, N, K);
return 0;
}
Stack
// C++ program to find element in stack
#include <bits/stdc++.h>
using namespace std;
// Function to find element in stack
void findElement(stack<int>& St, int K)
{
// Traverse the stack
while (!St.empty()) {
// Check if top is K
if (St.top() == K) {
cout << "Element found!";
return;
}
// Pop top element
St.pop();
}
cout << "Element Not found!";
}
// Driver Code
int main()
{
// Initialise stack
stack<int> St;
// Insert Element in stack
St.push(4);
St.push(3);
St.push(2);
St.push(1);
// Element to be found
int K = 3;
// Function Call
findElement(St, K);
return 0;
}
Queue
// C++ program to find given element
// in an queue
#include <bits/stdc++.h>
using namespace std;
// Function to find element in queue
void findElement(queue<int>& Q, int K)
{
// Traverse the stack
while (!Q.empty()) {
// Check if top is K
if (Q.front() == K) {
cout << "Element found!";
return;
}
// Pop top element
Q.pop();
}
cout << "Element Not found!";
}
// Driver Code
int main()
{
// Initialise queue
queue<int> Q;
// Insert element
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
// Element to be found
int K = 3;
// Print elements
findElement(Q, K);
return 0;
}
LinkedList
// C++ program to traverse the
// given linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
// Function that allocates a new
// node with given data
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// Function to insert a new node
// at the end of linked list
Node* insertEnd(Node* head, int data)
{
// If linked list is empty,
// Create a new node
if (head == NULL)
return newNode(data);
// If we have not reached the end
// Keep traversing recursively
else
head->next = insertEnd(head->next, data);
return head;
}
/// Function to traverse given LL
bool traverse(Node* head, int K)
{
if (head == NULL)
return false;
// If node with value K is found
// return true
if (head->data == K)
return true;
return traverse(head->next, K);
}
// Driver Code
int main()
{
// Given Linked List
Node* head = NULL;
head = insertEnd(head, 1);
head = insertEnd(head, 2);
head = insertEnd(head, 3);
head = insertEnd(head, 4);
// Element to be found
int K = 3;
// Function Call to traverse LL
if (traverse(head, K)) {
cout << "Element found!";
}
else {
cout << "Element Not found!";
}
}
Time Complexity: O(N)
Auxiliary Space: O(1)
- Insertion: It is the operation which we apply on all the data-structures. Insertion means to add an element in the given data structure. The operation of insertion is successful when the required element is added to the required data-structure. It is unsuccessful in some cases when the size of the data structure is full and when there is no space in the data-structure to add any additional element. The insertion has the same name as an insertion in the data-structure as an array, linked-list, graph, tree. In stack, this operation is called Push. In the queue, this operation is called Enqueue.
Below is the program to illustrate insertion in array, stack, queue and linkedlist :
Array
// C++ program for insertion in array
#include <iostream>
using namespace std;
// Function to print the array element
void printArray(int arr[], int N)
{
// Traverse the element of arr[]
for (int i = 0; i < N; i++) {
// Print the element
cout << arr[i] << ' ';
}
}
// Driver Code
int main()
{
// Initialise array
int arr[4];
// size of array
int N = 4;
// Insert elements in array
for (int i = 1; i < 5; i++) {
arr[i - 1] = i;
}
// Print array element
printArray(arr, N);
return 0;
}
Stack
// C++ program for insertion in array
#include <bits/stdc++.h>
using namespace std;
// Function to print the element in stack
void printStack(stack<int>& St)
{
// Traverse the stack
while (!St.empty()) {
// Print top element
cout << St.top() << ' ';
// Pop top element
St.pop();
}
}
// Driver Code
int main()
{
// Initialise stack
stack<int> St;
// Insert Element in stack
St.push(4);
St.push(3);
St.push(2);
St.push(1);
// Print elements in stack
printStack(St);
return 0;
}
Queue
// C++ program for insertion in queue
#include <bits/stdc++.h>
using namespace std;
// Function to print the
// element in queue
void printQueue(queue<int>& Q)
{
// Traverse the stack
while (!Q.empty()) {
// Print top element
cout << Q.front() << ' ';
// Pop top element
Q.pop();
}
}
// Driver Code
int main()
{
// Initialise queue
queue<int> Q;
// Insert element
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
// Print elements
printQueue(Q);
return 0;
}
LinkedList
// C++ program for insertion in LL
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
// Function that allocates a new
// node with given data
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// Function to insert a new node
// at the end of linked list
Node* insertEnd(Node* head, int data)
{
// If linked list is empty,
// Create a new node
if (head == NULL)
return newNode(data);
// If we have not reached the end
// Keep traversing recursively
else
head->next = insertEnd(head->next, data);
return head;
}
/// Function to traverse given LL
void traverse(Node* head)
{
if (head == NULL)
return;
// If head is not NULL,
// print current node and
// recur for remaining list
cout << head->data << " ";
traverse(head->next);
}
// Driver Code
int main()
{
// Given Linked List
Node* head = NULL;
head = insertEnd(head, 1);
head = insertEnd(head, 2);
head = insertEnd(head, 3);
head = insertEnd(head, 4);
// Function Call to traverse LL
traverse(head);
}
Time Complexity: O(N)
Auxiliary Space: O(1)
- Deletion: It is the operation which we apply on all the data-structures. Deletion means to delete an element in the given data structure. The operation of deletion is successful when the required element is deleted from the data structure. The deletion has the same name as a deletion in the data-structure as an array, linked-list, graph, tree, etc. In stack, this operation is called Pop. In Queue this operation is called Dequeue.
Below is the program to illustrate dequeue in Stack, Queue and Linkedlist:
Stack
// C++ program for insertion in array
#include <bits/stdc++.h>
using namespace std;
// Function to print the element in stack
void printStack(stack<int> St)
{
// Traverse the stack
while (!St.empty()) {
// Print top element
cout << St.top() << ' ';
// Pop top element
St.pop();
}
}
// Driver Code
int main()
{
// Initialise stack
stack<int> St;
// Insert Element in stack
St.push(4);
St.push(3);
St.push(2);
St.push(1);
// Print elements before pop
// operation on stack
printStack(St);
cout << endl;
// Pop the top element
St.pop();
// Print elements after pop
// operation on stack
printStack(St);
return 0;
}
Queue
// C++ program to illustrate dequeue
// in queue
#include <bits/stdc++.h>
using namespace std;
// Function to print the element
// of the queue
void printQueue(queue<int> myqueue)
{
// Traverse the queue and print
// element at the front of queue
while (!myqueue.empty()) {
// Print the first element
cout << myqueue.front() << ' ';
// Dequeue the element from the
// front of the queue
myqueue.pop();
}
}
// Driver Code
int main()
{
// Declare a queue
queue<int> myqueue;
// Insert element in queue from
// 0 to 5
for (int i = 1; i < 5; i++) {
// Insert element at the
// front of the queue
myqueue.push(i);
}
// Print element beforepop
// from queue
printQueue(myqueue);
cout << endl;
// Pop the front element
myqueue.pop();
// Print element after pop
// from queue
printQueue(myqueue);
return 0;
}
LinkedList
// C++ program for insertion in LL
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
// Function that allocates a new
// node with given data
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// Function to insert a new node
// at the end of linked list
Node* insertEnd(Node* head, int data)
{
// If linked list is empty,
// Create a new node
if (head == NULL)
return newNode(data);
// If we have not reached the end
// Keep traversing recursively
else
head->next = insertEnd(head->next, data);
return head;
}
/// Function to traverse given LL
void traverse(Node* head)
{
if (head == NULL)
return;
// If head is not NULL,
// print current node and
// recur for remaining list
cout << head->data << " ";
traverse(head->next);
}
// Driver Code
int main()
{
// Given Linked List
Node* head = NULL;
head = insertEnd(head, 1);
head = insertEnd(head, 2);
head = insertEnd(head, 3);
head = insertEnd(head, 4);
// Print before deleting the first
// element from LL
traverse(head);
// Move head pointer to forward
// to remove the first element
// If LL has more than 1 element
if (head->next != NULL) {
head = head->next;
}
else {
head = NULL;
}
cout << endl;
// Print after deleting the first
// element from LL
traverse(head);
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Some other method :
Create: -
It reserves memory for program elements by declaring them. The creation of data structure
Can be done during
- Compile-time
- Run-time.
You can use malloc() function.
Selection:-
It selects specific data from present data. You can select any specific data by giving condition in loop .
Update
It updates the data in the data structure. You can also update any specific data by giving some condition in loop like select approach.
Sort
Sorting data in a particular order (ascending or descending).
We can take the help of many sorting algorithms to sort data in less time. Example: bubble sort which takes O(n^2)time to sort data. There are many algorithms present like merge sort, insertion sort, selection sort, quick sort, etc.
Merge
Merging data of two different orders in a specific order may ascend or descend. We use merge sort to merge sort data.
Split Data
Dividing data into different sub-parts to make the process complete in less time.
Similar Reads
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Introduction to Data Structures
What is Data Structure?A data structure is a particular way of organising data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. The choice of a good data structure makes it possible to perform a variety of critical operations
7 min read
Data Structure Types, Classifications and Applications
A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently.A data structure organizes, processes, retrieves, and stores data, making it essential for nearly every program or software system. To
7 min read
Overview of Data Structures
Introduction to Linear Data Structures
Linear Data Structures are a type of data structure in computer science where data elements are arranged sequentially or linearly. Each element has a previous and next adjacent, except for the first and last elements. Characteristics of Linear Data Structure:Sequential Organization: In linear data s
8 min read
Introduction to Hierarchical Data Structure
We have discussed Overview of Array, Linked List, Queue and Stack. In this article following Data Structures are discussed. 5. Binary Tree 6. Binary Search Tree 7. Binary Heap 8. Hashing Binary Tree Unlike Arrays, Linked Lists, Stack, and queues, which are linear data structures, trees are hierarchi
13 min read
Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Introduction:Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.Trie: A trie, also known as a prefix tree, is a tree-like data structure that
10 min read
Different Types of Data Structures
Array Data Structure
Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul
3 min read
String in Data Structure
A string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
3 min read
Stack Data Structure
A Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
3 min read
Queue Data Structure
A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
3 min read
Introduction to Tree Data Structure
Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) or
15+ min read
Heap Data Structure
A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree.Basics
2 min read
Hashing in Data Structure
Hashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
3 min read
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure.BasicsGraph and its representationsBFS and DFS Breadth
3 min read
Matrix Data Structure
Matrix Data Structure is a two-dimensional array arranged in rows and columns. It is commonly used to represent mathematical matrices and is fundamental in various fields like mathematics, computer graphics, and data processing. Matrices allow for efficient storage and manipulation of data in a stru
2 min read
Advanced Data Structures
Advanced Data Structures refer to complex and specialized arrangements of data that enable efficient storage, retrieval, and manipulation of information in computer science and programming. These structures go beyond basic data types like arrays and lists, offering sophisticated ways to organize and
2 min read
Data Structure Alignment : How data is arranged and accessed in Computer Memory?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an
4 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two
4 min read
Static and Dynamic Data Structures
Data structures are the fundamental building blocks of computer programming. They determine how data is organized, stored, and manipulated within a software application. There are two main categories of data structures: static and dynamic. Static data structures have a fixed size and are allocated i
9 min read
Common operations on various Data Structures
Data Structure is the way of storing data in computer's memory so that it can be used easily and efficiently. There are different data-structures used for the storage of data. It can also be defined as a mathematical or logical model of a particular organization of data items. The representation of
15+ min read
Real-life Applications of Data Structures and Algorithms (DSA)
You may have heard that DSA is primarily used in the field of computer science. Although DSA is most commonly used in the computing field, its application is not restricted to it. The concept of DSA can also be found in everyday life. Here we'll address the common concept of DSA that we use in our d
10 min read