filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/data_structures/src/2d_array/rotate2darray.java
public class RotateMatrix { // function to rotate the matrix by 90 degrees clockwise static void rightRotate(int matrix[][], int n) { // determines the transpose of the matrix for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } // then we reverse the elements of each row for (int i = 0; i < n; i++) { // logic to reverse each row i.e 1D Array. int low = 0, high = n - 1; while (low < high) { int temp = matrix[i][low]; matrix[i][low] = matrix[i][high]; matrix[i][high] = temp; low++; high--; } } System.out.println("The 90 degree Rotated Matrix is: "); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(matrix[i][j] + " " + "\t"); } System.out.println(); } } // driver code public static void main(String args[]) { int n = 3; // initializing a 3*3 matrix with an illustration int matrix[][] = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; System.out.println("The Original Matrix is: "); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(matrix[i][j] + " " + "\t"); } System.out.println(); } // function calling rightRotate(matrix, n); } }
code/data_structures/src/2d_array/rotate_matrix.cpp
//#rotate square matrix by 90 degrees #include <bits/stdc++.h> #define n 5 using namespace std; void displayimage( int arr[n][n]); /* A function to * rotate a n x n matrix * by 90 degrees in * anti-clockwise direction */ void rotateimage(int arr[][n]) { // Performing Transpose for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) swap(arr[i][j], arr[j][i]); } // Reverse every row for (int i = 0; i < n; i++) reverse(arr[i], arr[i] + n); } // Function to print the matrix void displayimage(int arr[n][n]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << arr[i][j] << " "; cout << "\n"; } cout << "\n"; } int main() { int arr[n][n] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}; // displayimage(arr); rotateimage(arr); // Print rotated matrix displayimage(arr); return 0; } /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ /* Test Case 2 * int arr[n][n] = { * {1, 2, 3, 4}, * {5, 6, 7, 8}, * {9, 10, 11, 12}, * {13, 14, 15, 16} * }; */ /* Tese Case 3 *int mat[n][n] = { * {1, 2}, * {3, 4} * };*/ /* Time complexity : O(n*n) Space complexity: O(1) */
code/data_structures/src/2d_array/set_matrix_zero.cpp
#include <iostream> #include <string> #include <vector> #include <map> #include <cmath> #include <set> #include <unordered_map> #include <numeric> #include <algorithm> //#include <bits/stdc++.h> using namespace std; typedef long long ll; #define int int64_t int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } void setneg(vector<vector<int>> &matrix, int row, int col) { for (int i = 0; i < matrix.size(); ++i) if (matrix[i][col] != 0) matrix[i][col] = -2147483636; for (int j = 0; j < matrix[0].size(); ++j) if (matrix[row][j] != 0) matrix[row][j] = -2147483636; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while (t--) { // taking input of number of rows & coloums int n, m; cin >> n >> m; // creating a matrix of size n*m and taking input vector<vector<int>> matrix(n, vector<int>(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> matrix[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!matrix[i][j]) { setneg(matrix, i, j); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (matrix[i][j]==-2147483636) { matrix[i][j]=0; } } } cout<<endl; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout<<matrix[i][j]<<" "; } cout<<endl; } cout<<endl; } return 0; }
code/data_structures/src/3d_array/ThreeDArray.java
/** * This Java program demonstrates the creation and manipulation of a 3D array. * We will create a 3D array, initialize its elements, and print them. */ public class ThreeDArray { public static void main(String[] args) { // Define the dimensions of the 3D array int xSize = 3; // Size in the x-direction int ySize = 4; // Size in the y-direction int zSize = 2; // Size in the z-direction // Create a 3D array with the specified dimensions int[][][] threeDArray = new int[xSize][ySize][zSize]; // Initialize the elements of the 3D array int value = 1; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { for (int z = 0; z < zSize; z++) { threeDArray[x][y][z] = value; value++; } } } // Print the 3D array for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { for (int z = 0; z < zSize; z++) { System.out.println("threeDArray[" + x + "][" + y + "][" + z + "] = " + threeDArray[x][y][z]); } } } } }
code/data_structures/src/CircularLinkedList/circularLinkedList.cpp
#include <iostream> using namespace std; /** * A node will be consist of a int data & * a reference to the next node. * The node object will be used in making linked list */ class Node { public: int data; Node *next; }; /** * Using nodes for creating a circular linked list. * */ class CircularList { public: /** * stores the reference to the last node */ Node *last; /** * keeping predecessor reference while searching */ Node *preLoc; /** * current node reference while searching */ Node *loc; CircularList() { last = NULL; loc = NULL; preLoc = NULL; } /** * Checking if list empty */ bool isEmpty() { return last == NULL; } /** * Inserting new node in front */ void insertAtFront(int value) { Node *newnode = new Node(); newnode->data = value; if (isEmpty()) { newnode->next = newnode; last = newnode; } else { newnode->next = last->next; last->next = newnode; } } /** * Inserting new node in last */ void insertAtLast(int value) { Node *newnode = new Node(); newnode->data = value; if (isEmpty()) { newnode->next = newnode; last = newnode; } else { newnode->next = last->next; last->next = newnode; last = newnode; } } /** * Printing whole list iteratively */ void printList() { if (!isEmpty()) { Node *temp = last->next; do { cout << temp->data; if (temp != last) cout << " -> "; temp = temp->next; } while (temp != last->next); cout << endl; } else cout << "List is empty" << endl; } /** * Searching a value */ void search(int value) { loc = NULL; preLoc = NULL; if (isEmpty()) return; loc = last->next; preLoc = last; while (loc != last && loc->data < value) { preLoc = loc; loc = loc->next; } if (loc->data != value) { loc = NULL; // if(value > loc->data) // preLoc = last; } } /** * Inserting the value in its sorted postion in the list. */ void insertSorted(int value) { Node *newnode = new Node(); newnode->data = value; search(value); if (loc != NULL) { cout << "Value already exist!" << endl; return; } else { if (isEmpty()) insertAtFront(value); else if (value > last->data) insertAtLast(value); else if (value < last->next->data) insertAtFront(value); else { newnode->next = preLoc->next; preLoc->next = newnode; } } } void deleteValue(int value) { search(value); if (loc != NULL) { if (loc->next == loc) { last = NULL; } else if (value == last->data) { preLoc->next = last->next; last = preLoc; } else { preLoc->next = loc->next; } delete loc; } else cout << "Value not found" << endl; } void destroyList() { Node *temp = last->next; while (last->next != last) { temp = last->next; last->next = last->next->next; delete temp; } delete last; // delete the only remaining node last = NULL; } }; /** * Driver Code */ int main() { CircularList *list1 = new CircularList(); cout << "Initializing the list" << endl; list1->insertAtLast(2); list1->insertAtLast(3); list1->insertAtLast(4); list1->insertAtLast(6); list1->insertAtLast(8); list1->printList(); cout << "Inserting 5 in the list sorted" << endl; list1->insertSorted(5); list1->printList(); cout << "Deleting 3 from the list" << endl; list1->deleteValue(3); list1->printList(); cout << "Destroying the whole list" << endl; list1->destroyList(); list1->printList(); }
code/data_structures/src/CircularLinkedList/src_java/circularlinkedlist.java
class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } class CircularLinkedList { private Node head; // Constructor to create an empty circular linked list CircularLinkedList() { head = null; } // Function to insert a node at the end of the circular linked list void append(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; head.next = head; // Point back to itself for a single node circular list } else { Node temp = head; while (temp.next != head) { temp = temp.next; } temp.next = newNode; newNode.next = head; } } // Function to delete a node by value from the circular linked list void delete(int data) { if (head == null) return; // If the head node contains the value to be deleted if (head.data == data) { Node temp = head; while (temp.next != head) temp = temp.next; if (head == head.next) { head = null; // If there is only one node } else { head = head.next; temp.next = head; } return; } // Search for the node to delete Node current = head; Node prev = null; while (current.next != head && current.data != data) { prev = current; current = current.next; } // If the node with the given data was found if (current.data == data) { prev.next = current.next; } else { System.out.println("Node with data " + data + " not found in the list."); } } // Function to display the circular linked list void display() { if (head == null) return; Node temp = head; do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); System.out.println(); } public static void main(String[] args) { CircularLinkedList cll = new CircularLinkedList(); cll.append(1); cll.append(2); cll.append(3); System.out.print("Circular Linked List: "); cll.display(); // Output: 1 2 3 cll.delete(2); System.out.print("After deleting 2: "); cll.display(); // Output: 1 3 } }
code/data_structures/src/DoubleLinkedList/Doubly linked list.py
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DLL: def __init__(self): self.ptr = None def Insert(self, data): if self.ptr == None: self.ptr = Node(data) else: newnode = Node(data) current = self.ptr prev = None nextptr = current.next while current.data < newnode.data and current != None: prev = current current = current.next if current == None: break if current == None: prev.next = newnode newnode.prev = prev elif prev == None: newnode.next = self.ptr self.ptr = newnode else: prev.next = newnode newnode.next = current newnode.prev = prev current.prev = newnode def Display(self): temp = self.ptr while temp: print(temp.data, end="<->") temp = temp.next print("Null") def Delete(self, data): if self.ptr == None: print("List is Empty") return else: current = self.ptr prev = None while current.data != data and current != None: prev = current current = current.next if current == None: print("Item not found in List") return if prev == None: self.ptr = current.next current.prev = self.ptr else: prev.next = current.next current.prev = prev.next def Empty(self): return self.ptr == None dll = DLL() while True: choice = int(input("\n1.Insert\n2.Delete\n3.Check Empty\n4.Exit\nEnter Choice : ")) if choice == 1: value = int(input("Enter element to Insert : ")) dll.Insert(value) dll.Display() elif choice == 2: value = int(input("Enter element to Delete : ")) dll.Delete(value) dll.Display() elif choice == 3: print(dll.Empty()) elif choice == 4: break print("Program End")
code/data_structures/src/DoubleLinkedList/lru_cache_with_dll/src_go/main.go
/* - LRU cache implementation in Go - Change the 'capacity' variable to adjust the size of cache - Each node in the DLL can contain a key and a value - There are 2 main functions: 1. update(key, value): If the key-value pair is absent, then it will add it to the cache. If the key is already present, then it will update its value 2. get(key): It will print the key's value. If the key doesn't exist then it will print -1 - traverse() is an additional function that can be used to visualize the DLL - The attach() function is used to attach a node just after 'head' - The detach() function is used to detach a node */ package main import "fmt" const capacity int = 2 // Capacity of the cache. Change it accordingly type node struct{ data_key int data_val int next *node prev *node } var head *node var tail *node var tracker map[int]*node /////////////////////////////////////// // Helper functions // /////////////////////////////////////// func attach(block *node){ // Update the DLL block.next = head.next (head.next).prev = block head.next = block block.prev = head } func detach(block *node){ //Detach the block (block.prev).next = block.next (block.next).prev = block.prev } func update(key int, value int){ // If key is already present, then update the value v, found := tracker[key] if found{ v.data_val = value detach(v) attach(v) return } // If key is absent nodeToAdd := &node{ data_key: key, data_val:value } // The node/block to be inserted if len(tracker) == capacity{ nodeToRemove := tail.prev detach(nodeToRemove) delete(tracker, nodeToRemove.data_key) // Update the map accordingly attach(nodeToAdd) tracker[key] = nodeToAdd // Add the item to the map } else { attach(nodeToAdd) tracker[key] = nodeToAdd // Add the item to the map } } func get(key int){ // Return the value reqdNode, found := tracker[key] if found{ fmt.Printf("For key = %d, value = %d\n",key,reqdNode.data_val) } else { fmt.Printf("For key = %d, value = %d\n", key, -1) return } // Update the DLL detach(reqdNode) attach(reqdNode) } // Visualize the DLL func traverse(){ fmt.Println("\nHere's your DLL...") temp:=head.next for temp != tail{ fmt.Printf("(%d,%d) ", temp.data_key, temp.data_val) temp=temp.next } fmt.Println() } func main(){ head = &node{ data_key: 0, data_val: 0 } tail = &node{ data_key: 0, data_val: 0, prev: head } head.next = tail tracker = make(map[int]*node) // Sample Operations update(1, 1) update(2, 2) get(1) // prints 1 update(3,3) get(2) // prints -1 update(4,4) get(1) // prints -1 get(3) // prints 3 get(4) // prints 4 traverse() }
code/data_structures/src/DoubleLinkedList/src_c++/Doubly_LL.cpp
#include <iostream> using namespace std; struct Node { int data; Node* prev; Node* next; Node(int value) : data(value), prev(nullptr), next(nullptr) {} }; class DoublyLinkedList { private: Node* head; Node* tail; public: DoublyLinkedList() : head(nullptr), tail(nullptr) {} void insertAtTail(int value) { Node* newNode = new Node(value); if (tail == nullptr) { head = tail = newNode; } else { tail->next = newNode; newNode->prev = tail; tail = newNode; } } void insertAtHead(int value) { Node* newNode = new Node(value); if (head == nullptr) { head = tail = newNode; } else { head->prev = newNode; newNode->next = head; head = newNode; } } void printForward() { Node* current = head; while (current != nullptr) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; } void printBackward() { Node* current = tail; while (current != nullptr) { std::cout << current->data << " "; current = current->prev; } std::cout << std::endl; } }; int main() { DoublyLinkedList dll; int n; cout << "Enter the number of nodes in linked list: "; cin >> n; int x; cout << "Enter element no. 0: "; cin >> x; dll.insertAtHead(x); for(int i=1; i<n; i++) { int x; cout << "Enter element no. " << i << ": "; cin >> x; dll.insertAtTail(x); } std::cout << "Forward: "; dll.printForward(); // Output: 0 1 2 3 std::cout << "Backward: "; dll.printBackward(); // Output: 3 2 1 0 return 0; }
code/data_structures/src/DoubleLinkedList/src_cpp/doublylinkedlist.cpp
#include <iostream> class Node { public: int data; Node* next; Node* prev; Node(int val) { data = val; next = prev = nullptr; } }; class DoublyLinkedList { private: Node* head; Node* tail; public: DoublyLinkedList() { head = tail = nullptr; } // Insert at the end of the list void append(int val) { Node* newNode = new Node(val); if (!head) { head = tail = newNode; } else { tail->next = newNode; newNode->prev = tail; tail = newNode; } } // Insert at the beginning of the list void prepend(int val) { Node* newNode = new Node(val); if (!head) { head = tail = newNode; } else { head->prev = newNode; newNode->next = head; head = newNode; } } // Delete a node by its value void remove(int val) { Node* current = head; while (current) { if (current->data == val) { if (current == head) { head = head->next; if (head) head->prev = nullptr; } else if (current == tail) { tail = tail->prev; if (tail) tail->next = nullptr; } else { current->prev->next = current->next; current->next->prev = current->prev; } delete current; return; } current = current->next; } } // Display the list from head to tail void display() { Node* current = head; while (current) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; } }; int main() { DoublyLinkedList dll; dll.append(1); dll.append(2); dll.append(3); dll.prepend(0); dll.display(); // Output: 0 1 2 3 dll.remove(1); dll.display(); // Output: 0 2 3 return 0; }
code/data_structures/src/DoubleLinkedList/src_java/DoubleLinkedLists.java
public class DoubleLinkedLists { Node head; int size; public DoubleLinkedLists(){ head = null; size = 0; } public boolean isEmpty(){ return head == null; } public void addFirst(int item){ if(isEmpty()){ head = new Node(null, item, null); } else{ Node newNode = new Node(null, item, head); head.prev = newNode; head = newNode; } size++; } public void addLast(int item){ if(isEmpty()){ addFirst(item); } else{ Node current = head; while (current.next != null){ current = current.next; } Node newNode = new Node(current, item, null); current.next = newNode; size++; } } public void add(int item, int index) throws Exception { if(isEmpty()){ addFirst(item); } else if (index < 0 || index > size){ throw new Exception("Nilai indeks di luar batas"); } else{ Node current = head; int i = 0; while(i<index){ current = current.next; i++; } if(current.prev == null){ Node newNode = new Node(null, item, current); current.prev = newNode; head = newNode; } else{ Node newNode = new Node(current.prev, item, current); newNode.prev = current.prev; newNode.next = current; current.prev.next = newNode; current.prev = newNode; } } size++; } public int size(){ return size; } public void clear(){ head = null; size = 0; } public void print(){ if(!isEmpty()){ Node tmp = head; while(tmp != null){ System.out.print(tmp.data+"\t"); tmp = tmp.next; } System.out.println("\nberhasil diisi"); } else{ System.out.println("Linked Lists Kosong"); } } }
code/data_structures/src/DoubleLinkedList/src_java/DoubleLinkedListsMain.java
public class DoubleLinkedListsMain { public static void main(String[] args) throws Exception { DoubleLinkedLists dll = new DoubleLinkedLists(); dll.print(); System.out.println("Size : "+dll.size()); System.out.println("====================================="); dll.addFirst(3); dll.addLast(4); dll.addFirst(7); dll.print(); System.out.println("Size : "+dll.size()); System.out.println("====================================="); dll.add(40, 1); dll.print(); System.out.println("Size : "+dll.size()); System.out.println("====================================="); dll.clear(); dll.print(); System.out.println("Size : "+dll.size()); } }
code/data_structures/src/DoubleLinkedList/src_java/Node.java
public class Node{ int data; Node prev, next; Node(Node prev, int data, Node next){ this.prev= prev; this.data= data; this.next= next; } }
code/data_structures/src/Linked_List/Add_one_to_LL.cpp
class Solution { public: Node* reverse( Node *head) { // code here // return head of reversed list Node *prevNode=NULL,*currNode=head,*nextNode=head; while(currNode!=NULL){ nextNode=currNode->next; currNode->next=prevNode; prevNode=currNode; currNode=nextNode; } return prevNode; } Node* addOne(Node *head) { // Your Code here // return head of list after adding one if(head==NULL) return NULL; head=reverse(head); Node* node=head;int carry=1; while(node!=NULL){ int sum=carry+node->data; node->data=(sum%10); carry=sum/10; if(node->next==NULL) break; node=node->next; } if(carry) node->next=new Node(carry); return reverse(head); } };
code/data_structures/src/Linked_List/Count_nodes_of_Linked_List.cpp
// count the Number of Nodes n a Linked List int getCount(struct Node* head){ int cnt=0; Node *curr = head; while(curr != NULL){ cnt++; curr = curr->next; } return cnt; }
code/data_structures/src/Linked_List/Intersection_of_two_sorted_lists.cpp
Node* findIntersection(Node* head1, Node* head2) { if(head1==NULL or head2==NULL) return NULL; if(head1->data==head2->data) { head1->next=findIntersection(head1->next,head2->next); return head1; } else if(head1->data>head2->data) return findIntersection(head1,head2->next); else return findIntersection(head1->next,head2); }
code/data_structures/src/Linked_List/Remove_duplicates_in_unsorted_linked_list.cpp
// Removethe duplicate elements in the linked list Node * removeDuplicates( Node *head) { Node* temp1=head; Node* temp2=head->next; unordered_set<int> s; while(temp2!=NULL) { s.insert(temp1->data); if(s.find(temp2->data)!=s.end()) { Node* del=temp2; temp2=temp2->next; temp1->next=temp2; delete del; } else { temp1=temp1->next; temp2=temp2->next; } } return head; }
code/data_structures/src/Linked_List/add_two_numbers_represented_by_linked_lists.cpp
// { Driver Code Starts // driver #include <bits/stdc++.h> using namespace std; /* Linked list Node */ struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } }; struct Node* buildList(int size) { int val; cin>> val; Node* head = new Node(val); Node* tail = head; for(int i=0; i<size-1; i++) { cin>> val; tail->next = new Node(val); tail = tail->next; } return head; } void printList(Node* n) { while(n) { cout<< n->data << " "; n = n->next; } cout<< endl; } // } Driver Code Ends /* node for linked list: struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } }; */ class Solution { public: //Function to add two numbers represented by linked list. Node* reverse(Node* head){ Node* prev = NULL; Node* next = NULL; Node* current = head; while(current != NULL){ next = current->next; current->next = prev; prev = current; current = next; } return prev; } struct Node* addTwoLists(struct Node* first, struct Node* second){ first = reverse(first); second = reverse(second); Node* temp = NULL; Node* res = NULL; Node* cur = NULL; int carry = 0, sum = 0; while(first != NULL || second != NULL){ sum = carry + (first ? first->data : 0) + (second ? second->data : 0); carry = (sum>=10) ? 1 : 0; sum %= 10; temp = new Node(sum); if(res == NULL) res = temp; else cur->next = temp; cur = temp; if(first) first = first->next; if(second) second = second->next; } if(carry > 0){ temp = new Node(carry); cur->next = temp; cur = temp; } res = reverse(res); return res; } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n, m; cin>>n; Node* first = buildList(n); cin>>m; Node* second = buildList(m); Solution ob; Node* res = ob.addTwoLists(first,second); printList(res); } return 0; } // } Driver Code Ends
code/data_structures/src/Linked_List/creating_linked_list.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_beginning(int value, Node **start); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { // insert_in_beginning(arr[i], &start); insert_in_ending(arr[i], &start); } linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void insert_in_beginning(int value, Node **start) { Node *new_node = create_node(); new_node->data = value; new_node->next_pointer = *start; *start = new_node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; } /* Creating and inserting should be always insert_in_ending() for exam */
code/data_structures/src/Linked_List/deleting_a_node.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); void deleting(int value, Node **start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { insert_in_ending(arr[i], &start); } linked_list_print(start); deleting(5, &start); linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; } /* Deleting */ void deleting(int value, Node **start) { Node *current_node = *start; Node *next_node = current_node->next_pointer; if (current_node == NULL) { cout << "Underflow" << endl; exit(1); } else if (current_node->data == value) { *start = current_node->next_pointer; return; } while (current_node->next_pointer != NULL && next_node->data != value) { current_node = current_node->next_pointer; next_node = current_node->next_pointer; } current_node->next_pointer = next_node->next_pointer; free(next_node); }
code/data_structures/src/Linked_List/inserting_a_node.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_beginning(int value, Node **start); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { // insert_in_beginning(arr[i], &start); insert_in_ending(arr[i], &start); } linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void insert_in_beginning(int value, Node **start) { Node *new_node = create_node(); new_node->data = value; new_node->next_pointer = *start; *start = new_node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; }
code/data_structures/src/Linked_List/linked_list_palindrome.cpp
// Check if the liked list is palindrome or not bool checkpalindrome(vector<int> arr){ int s = 0; int e = arr.size() -1; while(s<=e){ if(arr[s] != arr[e]){ return 0; } s++; e--; } return 1; } bool isPalindrome(Node *head) { vector<int>arr; Node* temp = head; while(temp != NULL){ arr.push_back(temp -> data); temp = temp -> next; } return checkpalindrome(arr); }
code/data_structures/src/Linked_List/pairwise_swap_on_linked_list.cpp
// Swaps the data of linked list in pairs struct Node* pairwise_swap(struct Node* head) { Node* curr = head; while(curr!= NULL && curr->next != NULL){ swap(curr->data, curr->next->data); curr = curr->next->next; } return head; }
code/data_structures/src/Linked_List/remove_duplicate_element_from_sorted_linked_list.cpp
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; void print(Node *root) { Node *temp = root; while(temp!=NULL) { cout<<temp->data<<" "; temp=temp->next; } } Node* removeDuplicates(Node *root); int main() { // your code goes here int T; cin>>T; while(T--) { int K; cin>>K; Node *head = NULL; Node *temp = head; for(int i=0;i<K;i++){ int data; cin>>data; if(head==NULL) head=temp=new Node(data); else { temp->next = new Node(data); temp=temp->next; } } Node *result = removeDuplicates(head); print(result); cout<<endl; } return 0; }// } Driver Code Ends /* struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } };*/ //Function to remove duplicates from sorted linked list. Node *removeDuplicates(Node *head) { Node* current = head; Node* n; if (current == NULL) return head; while(current->next != NULL){ if(current->data == current->next->data){ n = current->next->next; free(current->next); current->next = n; } else current = current->next; } return head; }
code/data_structures/src/Linked_List/reverse_linked_list_in_k_groups.cpp
#include <iostream> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (k <= 1 || !head) { return head; // No need to reverse if k <= 1 or the list is empty. } ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* prev_group_tail = dummy; ListNode* current = head; while (true) { int count = 0; ListNode* group_start = current; ListNode* group_end = current; // Find the kth node in the group. while (count < k && group_end) { group_end = group_end->next; count++; } if (count < k || !group_end) { // If the remaining group has fewer than k nodes, stop. break; } ListNode* next_group_start = group_end->next; // Reverse the current group. ListNode* prev = next_group_start; ListNode* curr = group_start; while (curr != next_group_start) { ListNode* temp = curr->next; curr->next = prev; prev = curr; curr = temp; } prev_group_tail->next = group_end; group_start->next = next_group_start; prev_group_tail = group_start; current = next_group_start; } ListNode* new_head = dummy->next; delete dummy; return new_head; } }; // Helper function to create a linked list from an array. ListNode* createLinkedList(int arr[], int n) { if (n == 0) { return nullptr; } ListNode* head = new ListNode(arr[0]); ListNode* current = head; for (int i = 1; i < n; i++) { current->next = new ListNode(arr[i]); current = current->next; } return head; } // Helper function to print a linked list. void printLinkedList(ListNode* head) { ListNode* current = head; while (current != nullptr) { cout << current->val << " -> "; current = current->next; } cout << "nullptr" << endl; } int main() { int arr[] = {1, 2, 3, 4, 5}; int k = 2; ListNode* head = createLinkedList(arr, 5); Solution solution; ListNode* reversed = solution.reverseKGroup(head, k); printLinkedList(reversed); return 0; }
code/data_structures/src/Linked_List/reversing_linkedlist.cpp
#include<bits/stdc++.h> using namespace std; struct Node{ int value; struct Node* next; Node(int value){ this->value=value; next=NULL; } }; struct LL{ Node* head; LL(){ head=NULL; } void reverse(){ Node* curr=head; Node* prev=NULL,*next=NULL; while(curr!=NULL){ next=curr->next; curr->next=prev; prev=current; current=next; } head=prev; } void print(){ struct Node* temp=head; while(temp!=NULL){ cout<<temp->value<<" "; temp=temp->next; } } void push(int value){ Node* temp=new Node(value); temp->next=head; head=temp; } }; int main(){ LL obj; obj.push(5); obj.push(60); obj.push(4); obj.push(9); cout<<"Entered linked list is: "<<endl; obj.print(); obj.reverse(); cout<<"Reversed linked list is: "<<endl; obj.print(); return 0; } }
code/data_structures/src/Linked_List/sort_a_linked_list.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_beginning(int value, Node **start); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); void sort_linked_lis(Node **start); void insert_sorted_linked_list(int value, Node *start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { // insert_in_beginning(arr[i], &start); insert_in_ending(arr[i], &start); } linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; } void sort_linked_lis(Node **start) { Node *current_node = *start; Node *new_node = create_node(); *start = new_node; new_node->data = current_node->data; current_node = current_node->next_pointer; while (current_node != NULL) { insert_sorted_linked_list(current_node->data, *start); current_node = current_node->next_pointer; } } void insert_sorted_linked_list(int value, Node *start) { Node *current_node = start; while (current_node->next_pointer != NULL && current_node->data) { current_node = current_node->next_pointer; } }
code/data_structures/src/Linked_List/swap_nodes_in_pairs.cpp
ListNode* swapPairs(ListNode* head) { ListNode **pp = &head, *a, *b; while ((a = *pp) && (b = a->next)) { a->next = b->next; b->next = a; *pp = b; pp = &(a->next); } return head; }
code/data_structures/src/Linked_List/traverse_a_linked_list.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_beginning(int value, Node **start); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { // insert_in_beginning(arr[i], &start); insert_in_ending(arr[i], &start); } linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void insert_in_beginning(int value, Node **start) { Node *new_node = create_node(); new_node->data = value; new_node->next_pointer = *start; *start = new_node; } /* Traversing */ void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; }
code/data_structures/src/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/data_structures/src/bag/bag.cpp
//Needed for random and vector #include <vector> #include <string> #include <cstdlib> using std::string; using std::vector; //Bag Class Declaration class Bag { private: vector<string> items; int bagSize; public: Bag(); void add(string); bool isEmpty(); int sizeOfBag(); string remove(); }; /****************************************************************************** * Bag::Bag() * This is the constructor for Bag. It initializes the size variable. ******************************************************************************/ Bag::Bag() { bagSize = 0; } /****************************************************************************** * Bag::add * This function adds an item to the bag. ******************************************************************************/ void Bag::add(string item) { //Store item in last element of vector items.push_back(item); //Increase the size bagSize++; } /****************************************************************************** * Bag::isEmpty * This function returns true if the bag is empty and returns false if the * bag is not empty ******************************************************************************/ bool Bag::isEmpty(){ //True if(bagSize == 0){ return true; } //False else{ return false; } } /****************************************************************************** * Bag::size * This function returns the current number of items in the bag ******************************************************************************/ int Bag::sizeOfBag(){ return bagSize; } /****************************************************************************** * Bag::remove * This function removes a random item from the bag and returns which item was * removed from the bag ******************************************************************************/ string Bag::remove(){ //Get random item int randIndx = rand() % bagSize; string removed = items.at(randIndx); //Remove from bag items.erase(items.begin() + randIndx); bagSize--; //Return removed item return removed; }
code/data_structures/src/bag/bag.java
package bag.java; // Part of Cosmos by OpenGenus Foundation import java.util.Iterator; import java.util.NoSuchElementException; /** * Collection which does not allow removing elements (only collect and iterate) * * @param <Element> - the generic type of an element in this bag */ public class Bag<Element> implements Iterable<Element> { private Node<Element> firstElement; // first element of the bag private int size; // size of bag private static class Node<Element> { private Element content; private Node<Element> nextElement; } /** * Create an empty bag */ public Bag() { firstElement = null; size = 0; } /** * @return true if this bag is empty, false otherwise */ public boolean isEmpty() { return firstElement == null; } /** * @return the number of elements */ public int size() { return size; } /** * @param element - the element to add */ public void add(Element element) { Node<Element> oldfirst = firstElement; firstElement = new Node<>(); firstElement.content = element; firstElement.nextElement = oldfirst; size++; } /** * Checks if the bag contains a specific element * * @param element which you want to look for * @return true if bag contains element, otherwise false */ public boolean contains(Element element) { Iterator<Element> iterator = this.iterator(); while(iterator.hasNext()) { if (iterator.next().equals(element)) { return true; } } return false; } /** * @return an iterator that iterates over the elements in this bag in arbitrary order */ public Iterator<Element> iterator() { return new ListIterator<>(firstElement); } @SuppressWarnings("hiding") private class ListIterator<Element> implements Iterator<Element> { private Node<Element> currentElement; public ListIterator(Node<Element> firstElement) { currentElement = firstElement; } public boolean hasNext() { return currentElement != null; } /** * remove is not allowed in a bag */ @Override public void remove() { throw new UnsupportedOperationException(); } public Element next() { if (!hasNext()) throw new NoSuchElementException(); Element element = currentElement.content; currentElement = currentElement.nextElement; return element; } } /** * main-method for testing */ public static void main(String[] args) { Bag<String> bag = new Bag<>(); bag.add("1"); bag.add("1"); bag.add("2"); System.out.println("size of bag = " + bag.size()); for (String s : bag) { System.out.println(s); } System.out.println(bag.contains(null)); System.out.println(bag.contains("1")); System.out.println(bag.contains("3")); } }
code/data_structures/src/bag/bag.js
function Bag() { let bag = []; this.size = () => bag.length; this.add = item => bag.push(item); this.isEmpty = () => bag.length === 0; } let bag1 = new Bag(); console.log(bag1.size()); // 0 bag1.add("Blue ball"); console.log(bag1.size()); // 1 bag1.add("Red ball"); console.log(bag1.size()); // 2
code/data_structures/src/bag/bag.py
class Bag: """ Create a collection to add items and iterate over it. There is no method to remove items. """ # Initialize a bag as a list def __init__(self): self.bag = [] # Return the size of the bag def __len__(self): return len(self.bag) # Test if a item is in the bag def __contains__(self, item): return item in self.bag # Return a item in the bag by its index def __getitem__(self, key): return self.bag[key] # Add item to the bag def add(self, item): self.bag.append(item) # Return the bag showing all its items def items(self): return self.bag # Test if the bag is empty def isEmpty(self): return len(self.bag) == 0 ## Tests ## bag1 = Bag() print(len(bag1)) bag1.add("test") bag1.add("shamps") print(len(bag1)) print("bag1 is empty?", bag1.isEmpty()) print("test is in bag1", "test" in bag1) print("shampz is in bag1", "shampz" in bag1) for item in bag1: print(item) print(bag1.items())
code/data_structures/src/binary_heap/binary_heap.cpp
/* Binary Heap in C++ */ #include <iostream> #include <cstdlib> #include <vector> #include <iterator> class BinaryHeap{ private: std::vector <int> heap; int left(int parent); int right(int parent); int parent(int child); void heapifyup(int index); void heapifydown(int index); public: BinaryHeap() {} void Insert(int element); void DeleteMin(); int ExtractMin(); void DisplayHeap(); int Size(); }; // Return Heap Size int BinaryHeap::Size(){ return heap.size(); } // Insert Element into a Heap void BinaryHeap::Insert(int element){ heap.push_back(element); heapifyup(heap.size() -1); } // Delete Minimum Element void BinaryHeap::DeleteMin(){ if (heap.empty()){ std::cout << "Heap is Empty\n"; return; } heap[0] = heap.at(heap.size() - 1); heap.pop_back(); heapifydown(0); std::cout << "Element Deleted\n"; } // Extract Minimum Element int BinaryHeap::ExtractMin(){ if (heap.empty()) return -1; return heap.front(); } // Display Heap void BinaryHeap::DisplayHeap(){ std::vector <int>::iterator pos = heap.begin(); std::cout << "Heap --> "; while (pos != heap.end()){ std::cout << *pos << " "; pos++; } std::cout << "\n"; } // Return Left Child int BinaryHeap::left(int parent){ int l = 2 * parent + 1; if (l < heap.size()) return l; else return -1; } // Return Right Child int BinaryHeap::right(int parent){ int r = 2 * parent + 2; if (r < heap.size()) return r; else return -1; } // Return Parent int BinaryHeap::parent(int child){ int p = (child - 1)/2; if (child == 0) return -1; else return p; } // Heapify- Maintain Heap Structure bottom up void BinaryHeap::heapifyup(int in){ if (in >= 0 && parent(in) >= 0 && heap[parent(in)] > heap[in]){ int temp = heap[in]; heap[in] = heap[parent(in)]; heap[parent(in)] = temp; heapifyup(parent(in)); } } // Heapify- Maintain Heap Structure top down void BinaryHeap::heapifydown(int in){ int child = left(in); int child1 = right(in); if (child >= 0 && child1 >= 0 && heap[child] > heap[child1]){ child = child1; } if (child > 0 && heap[in] > heap[child]){ int temp = heap[in]; heap[in] = heap[child]; heap[child] = temp; heapifydown(child); } } int main(){ int choice, element; BinaryHeap h; while (true){ std::cout << "------------------\n"; std::cout << "Operations on Heap\n"; std::cout << "------------------\n"; std::cout << "1.Insert Element\n"; std::cout << "2.Delete Minimum Element\n"; std::cout << "3.Extract Minimum Element\n"; std::cout << "4.Print Heap\n"; std::cout << "5.Exit\n"; std::cout << "Enter your choice: "; std::cin >> choice; switch(choice){ case 1: std::cout << "Enter the element to be inserted: "; std::cin >> element; h.Insert(element); break; case 2: h.DeleteMin(); break; case 3: std::cout << "Minimum Element: "; if (h.ExtractMin() == -1){ std::cout << "Heap is Empty \n" ; } else std::cout << "Minimum Element: "<< h.ExtractMin() << "\n"; break; case 4: std::cout << "Displaying elements of Hwap: "; h.DisplayHeap(); break; case 5: return 1; default: std::cout << "Enter Correct Choice \n"; } } return 0; }
code/data_structures/src/binary_heap/binary_heap.dart
class Node { int priority; dynamic value; Node(this.priority, this.value); } class BinaryHeap { late List<Node> heap; BinaryHeap() { heap = []; } void insert(int priority, dynamic value) { final newNode = Node(priority, value); heap.add(newNode); _bubbleUp(heap.length - 1); } Node extractMin() { if (heap.isEmpty) { throw Exception("Heap is empty"); } final min = heap[0]; final last = heap.removeLast(); if (heap.isNotEmpty) { heap[0] = last; _heapify(0); } return min; } void _bubbleUp(int index) { while (index > 0) { final parentIndex = (index - 1) ~/ 2; if (heap[index].priority < heap[parentIndex].priority) { // Swap the elements if the current element has higher priority than its parent. final temp = heap[index]; heap[index] = heap[parentIndex]; heap[parentIndex] = temp; index = parentIndex; } else { break; } } } void _heapify(int index) { final leftChild = 2 * index + 1; final rightChild = 2 * index + 2; int smallest = index; if (leftChild < heap.length && heap[leftChild].priority < heap[index].priority) { smallest = leftChild; } if (rightChild < heap.length && heap[rightChild].priority < heap[smallest].priority) { smallest = rightChild; } if (smallest != index) { final temp = heap[index]; heap[index] = heap[smallest]; heap[smallest] = temp; _heapify(smallest); } } } void main() { final minHeap = BinaryHeap(); minHeap.insert(4, "A"); minHeap.insert(9, "B"); minHeap.insert(2, "C"); minHeap.insert(1, "D"); minHeap.insert(7, "E"); print("Extracted Min: ${minHeap.extractMin().value}"); // Should print "D" print("Extracted Min: ${minHeap.extractMin().value}"); // Should print "C" print("Extracted Min: ${minHeap.extractMin().value}"); // Should print "A" }
code/data_structures/src/binary_heap/binary_heap.py
class BinaryHeap: def __init__(self, size): self.List = (size) * [None] self.heapSize = 0 self.maxSize = size def peek(root): if not root: return else: return root.List[1] def sizeof(root): if not root: return else: return root.heapSize def heapifyTreeInsert(root, index): parentIndex = int(index/2) if index <= 1: return if root.List[index] < root.List[parentIndex]: temp = root.List[index] root.List[index] = root.List[parentIndex] root.List[parentIndex] = temp heapifyTreeInsert(root, parentIndex) def insert(root, nodeValue): if root.heapSize + 1 == root.maxSize: return "The Binary Heap is full." root.List[root.heapSize + 1] = nodeValue root.heapSize += 1 heapifyTreeInsert(root, root.heapSize) return "The node has been successfully inserted." def heapifyTreeExtract(root, index): leftIndex = index * 2 rightIndex = index * 2 + 1 swapChild = 0 if root.heapSize < leftIndex: return elif root.heapSize == leftIndex: if root.List[index] > root.List[leftIndex]: temp = root.List[index] root.List[index] = root.List[leftIndex] root.List[leftIndex] = temp return else: if root.List[leftIndex] < root.List[rightIndex]: swapChild = leftIndex else: swapChild = rightIndex if root.List[index] > root.List[swapChild]: temp = root.List[index] root.List[index] = root.List[swapChild] root.List[swapChild] = temp heapifyTreeExtract(root, swapChild) def extract(root): if root.heapSize == 0: return "The Binary Heap is empty." else: extractedNode = root.List[1] root.List[1] = root.List[root.heapSize] root.List[root.heapSize] = None root.heapSize -= 1 heapifyTreeExtract(root, 1) return extractedNode def DisplayHeap(root): print(root.List) B = BinaryHeap(5) insert(B, 70) DisplayHeap(B) insert(B, 40) DisplayHeap(B) extract(B) DisplayHeap(B) insert(B, 30) DisplayHeap(B) insert(B, 60) DisplayHeap(B) extract(B) DisplayHeap(B) insert(B, 5) DisplayHeap(B)
code/data_structures/src/disjoint_set/DisjointSet(DS).cpp
#include <iostream> using namespace std; int f[100]; int find(int node) { if(f[node] == node){ return node; } return f[node] = find(f[node]); //path compression } int union_set(int x,int y) { return f[find(x)]=find(y); } int main() { int arr[10]; for(int i=1;i<=10;i++){ arr[i - 1] = i; f[i] = i; } union_set(1, 3); union_set(4, 5); union_set(1, 2); union_set(1, 5); union_set(2, 8); union_set(9, 10); union_set(1, 9); union_set(2, 7); union_set(3, 6); for(auto a : arr){ cout<< a << "->" << f[a] <<"\n"; } return 0; }
code/data_structures/src/disjoint_set/DisjointSet_DS.py
f = [] f = [0 for x in range(100)] def find(f, node): if(f[node] == node): return node else: f[node] = find(f, f[node]) return f[node] def union_set(f, x, y): f[find(f, x)] = find(f, y) return f arr = [] arr = [0 for x in range(10)] for i in range(1,11): arr[i-1] = i f[i] = i union_set(f,1,3) union_set(f,4,5) union_set(f,1,2) union_set(f,1,5) union_set(f,2,8) union_set(f,9,10) union_set(f,1,9) union_set(f,2,7) union_set(f,3,6) for i in arr: print(f"{i}->{f[i]}\n")
code/data_structures/src/disjoint_set/README.md
<h1>DISJOINT SET</h1> <h2>Description</h2> <h3>Disjoint set is a data structure that stores a collection of disjoint (non-overlapping) sets. Equivalently, it stores a partition of a set into disjoint subsets. It provides operations for adding new sets, merging sets (replacing them by their union), and finding a representative member of a set.</h3> <h2>Functions</h2> <h3>Union() : Join two subsets into a single subset.</h3> <h3>Find() : Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset.</h3> <h2>Time Complexity</h2> <h3>Union() : O(n) </h3> <h3>Find() : O(n) [Without path compression]</h3> <h3>Find() : O(log n) [With path compression]</h3>
code/data_structures/src/graph/graph.py
class Graph: def __init__(self): #dictionary where keys are vertices and values are lists of adjacent vertices self.vertDict = {} def insert_vertex(self, vertex): if vertex not in self.vertDict: self.vertDict[vertex] = [] def add_edge(self, vertex1, vertex2, directed=False): if vertex1 not in self.vertDict: self.insert_vertex(vertex1) if vertex2 not in self.vertDict: self.insert_vertex[vertex2] self.vertDict[vertex1].append(vertex2) #if the graph is undirected, add to both's adjacency lists if not directed: self.vertDict[vertex2].append(vertex1) def delete_edge(self, vertex1, vertex2, directed=False): if vertex1 in self.vertDict and vertex2 in self.vertDict[vertex1]: self.vertDict[vertex1].remove(vertex2) if not directed and vertex2 in self.vertDict and vertex1 in self.vertDict[vertex2]: self.vertDict[vertex2].remove(vertex1) def delete_vertex(self, vertex): if vertex in self.vertDict: for i in self.vertDict: if vertex in self.vertDict[i]: self.vertDict[i].remove(vertex) del self.vertDict[vertex] def get_neighbors(self, vertex): return self.vertDict.get(vertex, []) def printGraph(self): for i, j in self.vertDict.items(): print("{vertex}: {neighbors}") tester = Graph() tester.insert_vertex("A") tester.insert_vertex("B") tester.insert_vertex("C") tester.add_edge("A", "B") tester.add_edge("A", "C") tester.add_edge("B", "C") tester.printGraph() print("Neighbors of A:", tester.get_neighbors("A")) tester.delete_edge("A", "B") tester.printGraph() tester.delete_vertex("C") print("next") tester.printGraph()
code/data_structures/src/hashs/bloom_filter/README.md
Bloom Filter --- A space-efficient probabilistic data structure that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not; i.e. a query returns either "possibly in set" or "definitely not in set". Elements can be added to the set, but not removed. ## Api * `Add(item)`: Adds the item into the set * `Check(item) bool`: Check if the item possibly exists into the set ## Complexity **Time** If we are using a bloom filter with bits and hash function, insertion and search will both take time. In both cases, we just need to run the input through all of the hash functions. Then we just check the output bits. | Operation | Complexity | |---|---| | insertion | O(k) | | search | O(k) | **Space** The space of the actual data structure (what holds the data). | Complexity | |---| | O(m) | Where `m` is the size of the slice.
code/data_structures/src/hashs/bloom_filter/bloom_filter.c
#include <stdio.h> #include <stdlib.h> typedef struct st_BloomFilter { int size; char *bits; } BloomFilter; // Declare interface BloomFilter* bl_init(int size); void bl_add(BloomFilter *bl, int value); int bl_contains(BloomFilter *bl, int value); void bl_destroy(BloomFilter *bl); // Implementation BloomFilter* bl_init(int size) { BloomFilter *bl = (BloomFilter*)malloc(sizeof(BloomFilter)); bl->size = size; bl->bits = (char*)malloc(size/8 + 1); return bl; } void bl_add(BloomFilter *bl, int value) { int hash = value % bl->size; bl->bits[hash / 8] |= 1 << (hash % 8); } int bl_contains(BloomFilter *bl, int value) { int hash = value % bl->size; return (bl->bits[hash / 8] & (1 << (hash % 8))) != 0; } void bl_destroy(BloomFilter *bl) { free(bl->bits); free(bl); } int main() { BloomFilter *bl = bl_init(1000); bl_add(bl, 1); bl_add(bl, 2); bl_add(bl, 1001); bl_add(bl, 1004); if(bl_contains(bl, 1)) printf("bloomfilter contains 1\n"); if(bl_contains(bl, 2)) printf("bloomfilter contains 2\n"); if(!bl_contains(bl, 3)) printf("bloomfilter not contains 3\n"); if(bl_contains(bl, 4)) printf("bloomfilter not contains 4, but return false positive\n"); }
code/data_structures/src/hashs/bloom_filter/bloom_filter.cpp
#include <iostream> using namespace std; class BloomFilter { public: BloomFilter(int size) { size_ = size; bits_ = new char[size_ / 8 + 1]; } ~BloomFilter() { delete [] bits_; } void Add(int value) { int hash = value % size_; bits_[hash / 8] |= 1 << (hash % 8); } bool Contains(int value) { int hash = value % size_; return (bits_[hash / 8] & (1 << (hash % 8))) != 0; } private: char* bits_; int size_; }; int main() { BloomFilter bloomFilter(1000); bloomFilter.Add(1); bloomFilter.Add(2); bloomFilter.Add(1001); bloomFilter.Add(1004); if (bloomFilter.Contains(1)) cout << "bloomFilter contains 1" << endl; if (bloomFilter.Contains(2)) cout << "bloomFilter contains 2" << endl; if (!bloomFilter.Contains(3)) cout << "bloomFilter not contains 3" << endl; if (bloomFilter.Contains(4)) cout << "bloomFilter not contains 4, but return false positive" << endl; }
code/data_structures/src/hashs/bloom_filter/bloom_filter.go
package main import ( "fmt" "hash" "hash/fnv" "github.com/spaolacci/murmur3" ) // Minimal interface that the Bloom filter must implement type Interface interface { Add(item []byte) // Adds the item into the Set Check(item []byte) bool // Performs probabilist test if the item exists in the set or not. } // BloomFilter probabilistic data structure definition type BloomFilter struct { bitset []bool // The bloom-filter bitset k uint // Number of hash values n uint // Number of elements in the filter m uint // Size of the bloom filter hashfns []hash.Hash64 // The hash functions } // Returns a new BloomFilter object, func New(size, numHashValues uint) *BloomFilter { return &BloomFilter{ bitset: make([]bool, size), k: numHashValues, m: size, n: uint(0), hashfns: []hash.Hash64{murmur3.New64(), fnv.New64(), fnv.New64a()}, } } // Adds the item into the bloom filter set by hashing in over the hash functions func (bf *BloomFilter) Add(item []byte) { hashes := bf.hashValues(item) i := uint(0) for { if i >= bf.k { break } position := uint(hashes[i]) % bf.m bf.bitset[uint(position)] = true i += 1 } bf.n += 1 } // Test if the item into the bloom filter is set by hashing in over the hash functions func (bf *BloomFilter) Check(item []byte) (exists bool) { hashes := bf.hashValues(item) i := uint(0) exists = true for { if i >= bf.k { break } position := uint(hashes[i]) % bf.m if !bf.bitset[uint(position)] { exists = false break } i += 1 } return } // Calculates all the hash values by hashing in over the hash functions func (bf *BloomFilter) hashValues(item []byte) []uint64 { var result []uint64 for _, hashFunc := range bf.hashfns { hashFunc.Write(item) result = append(result, hashFunc.Sum64()) hashFunc.Reset() } return result } func main() { bf := New(1024, 3) bf.Add([]byte("hello")) bf.Add([]byte("world")) bf.Add([]byte("1234")) bf.Add([]byte("hello-world")) fmt.Printf("hello in bloom filter = %t \n", bf.Check([]byte("hello"))) fmt.Printf("world in bloom filter = %t \n", bf.Check([]byte("world"))) fmt.Printf("helloworld in bloom filter = %t \n", bf.Check([]byte("helloworld"))) fmt.Printf("1 in bloom filter = %t \n", bf.Check([]byte("1"))) fmt.Printf("2 in bloom filter = %t \n", bf.Check([]byte("2"))) fmt.Printf("3 in bloom filter = %t \n", bf.Check([]byte("3"))) }
code/data_structures/src/hashs/bloom_filter/bloom_filter.java
/** * Project: Cosmos * Package: main * File: BloomFilter.java * * @author sidmishraw * Last modified: Oct 18, 2017 6:25:58 PM */ package main; import java.util.ArrayList; import java.util.List; /** * <p> * {@link BloomFilter} This is a unoptimized version of a Bloom filter. A Bloom * filter is a data structure designed to tell you, rapidly and * memory-efficiently, whether an element is present in a set. The price paid * for this efficiency is that a Bloom filter is a <i>probabilistic data * structure</i>: it tells us that the element either definitely is not in the * set or may be in the set. * * For more information see: * <a href="https://llimllib.github.io/bloomfilter-tutorial/"> Bloom filter * tutorial</a> * * This implementation is going to have 2 hash functions: * FNV and FNV-1a hashes. * * @author sidmishraw * * Qualified Name: * main.BloomFilter * */ public class BloomFilter { /** * Default bit vector size for the {@link BloomFilter} */ private static final int BIT_VECTOR_SIZE = 16; /** * <p> * This is the base data structure of a bloom filter. * * <p> * To add an element to the Bloom filter, we simply hash it a few times and * set the bits in the bit vector at the index of those hashes to true. * * <p> * To test for membership, you simply hash the object with the same hash * functions, then see if those values are set in the bit vector. If they * aren't, you know that the element isn't in the set. If they are, you only * know that it might be, because another element or some combination of * other elements could have set the same bits. */ private boolean[] bitvector; /** * The list of hash functions used by the bloom filter */ private List<HashFunction> hashFunctions; /** * The number of elements added to the bloom filter, this influences the * probability of membership of an element, when checking membership. */ private int nbrElements; /** * */ public BloomFilter() { this.bitvector = new boolean[BIT_VECTOR_SIZE]; this.nbrElements = 0; this.hashFunctions = new ArrayList<>(); this.hashFunctions.add(BloomFilter::fnv); // passing in the method // reference // this.hashFunctions.add(this::fvn1a); // passing in the method // reference, // // for the instance } /** * Creates and initializes a new Bloom filter with `m` slots in the bit * vector table * * @param m * The size of the bit vector of the bloom filter * @param hashFunctions * The hash functions to be used by the bloom filter for */ public BloomFilter(int m, HashFunction... hashFunctions) { this.bitvector = new boolean[m]; this.nbrElements = 0; this.hashFunctions = new ArrayList<>(); for (HashFunction func : hashFunctions) { this.hashFunctions.add(func); } if (this.hashFunctions.size() == 0) { this.hashFunctions.add(BloomFilter::fnv); } } /** * <p> * Adds the element into the bloom filter. To get added, it must pass * through the k hash functions of the bloom filter. * * T:: O(k); where k is the number of hash functions * * @param element * The element */ public void add(Stringable element) { byte[] toBeHashed = element.stringValue().getBytes(); for (HashFunction hFunc : this.hashFunctions) { long hash = hFunc.hash(toBeHashed); this.bitvector[(int) (hash % this.bitvector.length)] = true; } this.nbrElements++; } /** * <p> * Checks if the element is a member of the bloom filter. * T:: O(k); where k is the number of hash functions * * @param element * The element that needs to be checked for membership * @return The result containing the probability of membership and if it is * a member. The result is a valid JSON string of form * <code> * { * "probability": "1", * "isMember": "false" * } * </code> */ public String check(Stringable element) { byte[] toBeHashed = element.stringValue().getBytes(); boolean isMember = true; for (HashFunction hFunc : this.hashFunctions) { long hash = hFunc.hash(toBeHashed); isMember = isMember && this.bitvector[(int) (hash % this.bitvector.length)]; } if (isMember) { return calcProbability(); } else { return "{\"probability\": 1, \"isMember\": false}"; } } /** * Computes the probability of membership using the formula : (1-e^-kn/m)^k * where ^ is exponentation and * m = number of bits in the bit vector table * n = number of elements in the bloom filter * k = number of hash functions * * @return The membership probability, json */ private final String calcProbability() { Double prob = Math.pow( (1 - Math.exp(((-1) * this.hashFunctions.size() * this.nbrElements) / (double) this.bitvector.length)), this.hashFunctions.size()); return String.format("{\"probability\": %s, \"isMember\": true}", prob); } /** * <p> * Fetches m of the bloom filter * * @return The number of bits in the bit vector backing the bloom filter */ public int getM() { return this.bitvector.length; } /** * <p> * Fetches k of the bloom filter * * @return The number of hash functions of the bloom filter */ public int getK() { return this.hashFunctions.size(); } /** * <p> * Fetches n of the bloom filter * * @return The number of elements added to the bloom filter */ public int getN() { return this.nbrElements; } /** * Just for testing */ @Override public String toString() { StringBuffer buf = new StringBuffer(); if (this.bitvector.length > 0) { buf.append("["); buf.append(String.format("(%d,%s)", 0, this.bitvector[0])); } for (int i = 1; i < this.bitvector.length; i++) { buf.append(String.format(",(%d,%s)", i, this.bitvector[i])); } buf.append("]"); return buf.toString(); } /** * <p> * {@link Stringable} are things that can give be made into a String. * * @author sidmishraw * * Qualified Name: * main.Stringable * */ public static interface Stringable { public String stringValue(); } /** * <p> * The hashfunctions that can be used by the bloom filter * * @author sidmishraw * * Qualified Name: * main.HashFunction * */ @FunctionalInterface public static interface HashFunction { /** * Hashes the element(byte buffer) to an int * * @param buffer * The byte buffer of the element to be hashed * @return The hashed number */ public long hash(byte[] buffer); } /** * The FNV hash function: * Uses the 32 bit FNV prime and FNV_OFFSET * * FNV hashing using the FNVHash - v1 see * <a href="http://isthe.com/chongo/tech/comp/fnv/#history">link</a>, * uses: * 32 bit offset basis = 2166136261 * 32 bit FNV_prime = 224 + 28 + 0x93 = 16777619 * * @param buffer * The element to be hashed in bytes * @return The 32 bit FNV hash of the element */ public static final long fnv(byte[] buffer) { final long OFFSET_BASIS_32 = 2166136261L; final long FNV_PRIME_32 = 16777619L; long hash = OFFSET_BASIS_32; for (byte b : buffer) { hash = hash * FNV_PRIME_32; hash = hash ^ b; } return Math.abs(hash); } /** * The FNV-1a hash function: * USes the 32 bit FNV prime and FNV_Offset * * @param buffer * The element to be hased, in bytes * @return The 32 bit FNV-1a hash of the element */ public static final long fnv1a(byte[] buffer) { final long OFFSET_BASIS_32 = 2166136261L; final long FNV_PRIME_32 = 16777619L; long hash = OFFSET_BASIS_32; for (byte b : buffer) { hash = hash ^ b; hash = hash * FNV_PRIME_32; } return Math.abs(hash); } /** * For testing out the library * * @param args */ public static void main(String[] args) { BloomFilter b = new BloomFilter(15); System.out.println("FNV hash of 'hello' = " + BloomFilter.fnv("hello".getBytes()) % b.bitvector.length); System.out.println("FNV-1a hash of 'hello' = " + BloomFilter.fnv1a("hello".getBytes()) % b.bitvector.length); b.add(() -> "hello"); b.add(() -> "helloWorld"); b.add(() -> "helloDear"); b.add(() -> "her"); b.add(() -> "3456"); System.out.println("hello in bloom filter = " + b.check(() -> "hello")); System.out.println("helloWorld in bloom filter = " + b.check(() -> "helloWorld")); System.out.println("helloDear in bloom filter = " + b.check(() -> "helloDear")); System.out.println("dear in bloom filter = " + b.check(() -> "dear")); System.out.println("3456 in bloom filter = " + b.check(() -> "3456")); System.out.println("3 in bloom filter = " + b.check(() -> "3")); System.out.println("4 in bloom filter = " + b.check(() -> "4")); System.out.println("5 in bloom filter = " + b.check(() -> "5")); System.out.println("6 in bloom filter = " + b.check(() -> "6")); } }
code/data_structures/src/hashs/bloom_filter/bloom_filter.js
/** * bloom_filter.js * @author Sidharth Mishra * @description Bloom filter in Javascript(Node.js), to be used with Node.js for testing. For `OpenGenus/cosmos` * @created Wed Oct 18 2017 19:31:29 GMT-0700 (PDT) * @copyright 2017 Sidharth Mishra * @last-modified Wed Oct 18 2017 19:31:32 GMT-0700 (PDT) */ /** * bf -- Bloom Filter utilities, uses FNV and FNV-1a hash algorithms for now. * Future work: Added hash mix with Murmur3 hash * * Addition into bloom filter: Time Complexity : O(k) where k = number of hash functions * Checking membership: Time Complexity : O(k) where k = number of hash functions */ (function(bfilter) { /** * Makes a new bloom filter. Uses FNV Hash as the hash function. This implementation uses only * FNV Hash functions for now. * FNV hash versions: * -> FNV * -> FNV 1a * * :Future work: * Add Murmur3 hash function. * * @param {number} m The number of bits in the Bit Vector backing the bloom filter * @param {[Function]} k the hash functions to be used * * @returns {bfilter.BloomFilter} a bloom filter with m bits and k hash functions */ bfilter.BloomFilter = function BloomFilter(m, k) { if ( arguments.length < 2 || undefined == m || undefined == k || undefined == k.length || k.length == 0 || typeof k !== "object" ) { throw new Error("Couldn't construct a bloom filter, bad args"); } // count of number of elements inserted into the bloom filter this.nbrElementsInserted = 0; this.bitVector = []; // the bit vector this.hashFunctions = k; // the list of hash functions to use for adding and testing membership // make the bit vector with m bits for (let i = 0; i < m; i++) { this.bitVector.push(false); } for (let i = 0; i < this.hashFunctions.length; i++) { if (typeof this.hashFunctions[i] !== "function") { throw new Error("Hash function is not a function"); } } }; /** * FNV hashing using the FNVHash - v1a see link: http://isthe.com/chongo/tech/comp/fnv/#history, * uses: * 32 bit offset basis = 2166136261 * 32 bit FNV_prime = 224 + 28 + 0x93 = 16777619 * @param {Buffer} toBeHashed The element to be hashed, Node.js buffer */ bfilter.fnvHash1a = function(toBeHashed) { const OFFSET_BASIS_32 = 2166136261; const FNV_PRIME = 16777619; let hash = OFFSET_BASIS_32; // 32 bit offset basis // or each octet_of_data to be hashed // toBeHashed is a Buffer that has octets of data to be hashed for (let i = 0; i < toBeHashed.length; i++) { hash = hash ^ toBeHashed[i]; hash = hash * FNV_PRIME; } // since hash being returned is negative most of the times return Math.abs(hash); }; /** * FNV hashing using the FNVHash - v1 see link: http://isthe.com/chongo/tech/comp/fnv/#history, * uses: * 32 bit offset basis = 2166136261 * 32 bit FNV_prime = 224 + 28 + 0x93 = 16777619 * @param {Buffer} toBeHashed The element to be hashed, Node.js buffer */ bfilter.fnvHash = function(toBeHashed) { const OFFSET_BASIS_32 = 2166136261; const FNV_PRIME = 16777619; let hash = OFFSET_BASIS_32; // 32 bit offset basis // or each octet_of_data to be hashed // toBeHashed is a Buffer that has octets of data to be hashed for (let i = 0; i < toBeHashed.length; i++) { hash = hash * FNV_PRIME; hash = hash ^ toBeHashed[i]; } // since hash being returned is negative most of the times return Math.abs(hash); }; /** * Adds the element to the bloom filter. When an element is added to the bloom filter, it gets through * the k different hash functions; i.e it gets hashed k times. * T:: O(k) operation * @param {string} element The element is converted bits and then hashed k times before getting added * to the bit vector. */ bfilter.BloomFilter.prototype.add = function(element) { // console.log(JSON.stringify(this)); if (typeof element !== "string") { element = String(element); } let buffE = Buffer.from(element); // get the element buffer let hash = null; for (let i = 0; i < this.hashFunctions.length; i++) { hash = this.hashFunctions[i](buffE); // update the bit vector's index // depending on the hash value this.bitVector[hash % this.bitVector.length] = true; } this.nbrElementsInserted += 1; }; /** * Check if the element is in the bloom filter. * T:: O(k) operation * @param {string} element The element that needs to get its membership verified */ bfilter.BloomFilter.prototype.check = function(element) { if (typeof element !== "string") { element = String(element); } let buffE = Buffer.from(element); // get the element buffer let hash = null; let prob = true; for (let i = 0; i < this.hashFunctions.length; i++) { hash = this.hashFunctions[i](buffE); // checking membership by ANDing the bits in the bitVector prob = prob && this.bitVector[hash % this.bitVector.length]; } if (prob) { return { probability: calcProb( this.bitVector.length, this.hashFunctions.length, this.nbrElementsInserted ), isMember: prob }; } else { return { probability: 1, isMember: prob }; } }; /** * * Computes the probabilty of membership in the bloom filter = (1-e^-kn/m)^k * where ^ is exponentation * * @param {*} m The number of bits in the bit vector * @param {*} k The number of hash functions * @param {*} n The number of elements added to the bloom filter * * @returns {number} The probability of membership */ function calcProb(m, k, n) { return Math.pow(1 - Math.exp((-1 * k * n) / m), k); } })((bf = {})); // exports the bf -- bloom filter utilities module.exports.bf = bf; /** * Tests * * @param {number} m The size of bit vector backing the bloom filter * @param {[Function]} k The nunber of times the element needs to be hashed */ function test(m, k) { let bloomFilter = new bf.BloomFilter(m, k); bloomFilter.add("hello"); bloomFilter.add("helloWorld"); bloomFilter.add("helloDear"); bloomFilter.add("her"); bloomFilter.add("3456"); console.log( `hello in bloom filter = ${JSON.stringify(bloomFilter.check("hello"))}` ); console.log( `helloWorld in bloom filter = ${JSON.stringify( bloomFilter.check("helloWorld") )}` ); console.log( `helloDear in bloom filter = ${JSON.stringify( bloomFilter.check("helloDear") )}` ); console.log( `world in bloom filter = ${JSON.stringify(bloomFilter.check("world"))}` ); console.log( `123 in bloom filter = ${JSON.stringify(bloomFilter.check("123"))}` ); console.log( `Number(3456) in bloom filter = ${JSON.stringify(bloomFilter.check(3456))}` ); console.log( `Number(3) in bloom filter = ${JSON.stringify(bloomFilter.check(3))}` ); console.log( `Number(4) in bloom filter = ${JSON.stringify(bloomFilter.check(4))}` ); console.log( `Number(5) in bloom filter = ${JSON.stringify(bloomFilter.check(5))}` ); console.log( `Number(6) in bloom filter = ${JSON.stringify(bloomFilter.check(6))}` ); } // some tests console.log("---------- test 1 ----------"); try { test(32); } catch (e) { console.log("Test 1 passed!"); } console.log("---------- test 2 ----------"); try { test(4, [bf.fnvHash, 55]); } catch (e) { console.log("Test 2 passed!"); } console.log("---------- test 3 ----------"); try { test(15, [bf.fnvHash1a]); console.log("Test 3a passed! ---"); test(15, [bf.fnvHash]); console.log("Test 3b passed!"); } catch (e) { console.log(e); } console.log("---------- test 4 ----------"); try { test(64, [bf.fnvHash1a]); console.log("Test 4 passed!"); } catch (e) { console.log(e); } console.log("---------- test 5 ----------"); try { test(32, [bf.fnvHash1a, bf.fnvHash1a, bf.fnvHash, bf.fnvHash1a]); console.log("Test 5 passed!"); } catch (e) { console.log(e); } console.log("---------- test 6 ----------"); try { test(32, 6); } catch (e) { console.log("Test 6 passed!"); } console.log("---------- test 7 ----------"); try { test(32, [bf.fnvHash1a, bf.fnvHash1a, bf.fnvHash1a, bf.fnvHash1a]); console.log("Test 7 passed!"); } catch (e) { console.log(e); } // console.log(bf.fnvHash(Buffer.from("hello")) % 15);
code/data_structures/src/hashs/bloom_filter/bloom_filter.py
# Part of Cosmos by OpenGenus Foundation # A Bloom filter implementation in python class bloomFilter: def __init__(self, size=1000, hashFunctions=None): """ Construct a bloom filter with size bits(default: 1000) and the associated hashFunctions. Default hash function is i.e. hash(e)%size. """ self.bits = 0 self.M = size if hashFunctions is None: self.k = 1 self.hashFunctions = [lambda e, size: hash(e) % size] else: self.k = len(hashFunctions) self.hashFunctions = hashFunctions def add(self, value): """ Insert value in bloom filter""" for hf in self.hashFunctions: self.bits |= 1 << hf(value, self.M) def __contains__(self, value): """ Determine whether a value is present. A false positive might be returned even if the element is not present. However, a false negative will never be returned. """ for hf in self.hashFunctions: if self.bits & 1 << hf(value, self.M) == 0: return False return True # Example of usage bf = bloomFilter() bf.add("Francis") bf.add("Claire") bf.add("Underwood") if "Francis" in bf: print("Francis is in BloomFilter :)") if "Zoe" not in bf: print("Zoe is not in BloomFilter :(")
code/data_structures/src/hashs/bloom_filter/bloom_filter.scala
import collection.immutable.BitSet object BloomFilter { def apply[T](size: Int): Option[BloomFilter[T]] = { if (size < 0) None Some(BloomFilter[T](size, BitSet.empty)) } } case class BloomFilter[T](size: Int, bitSet: BitSet) { def defaultIndicies(item: T): (Int, Int) = { val hash = item.hashCode() val hash2 = (hash >> 16) | (hash << 16) (Math.floorMod(hash, size), Math.floorMod(hash2, size)) } def add(item: T): BloomFilter[T] = { val (h1, h2) = defaultIndicies(item) BloomFilter(size, bitSet.+(h1, h2)) } def contains(item: T): Boolean = { val (h1, h2) = defaultIndicies(item) bitSet.contains(h1) && bitSet.contains(h2) } } object Main { def main(args: Array[String]): Unit = { println(BloomFilter[Int](100).get.add(5)) println(BloomFilter[Int](100).get.add(5).contains(5)) println(BloomFilter[Int](100).get.add(5).contains(6)) println(BloomFilter[Int](100).get.add(5).add(7)) println(BloomFilter[Int](100).get.add(5).add(7).contains(5)) println(BloomFilter[Int](100).get.add(5).add(7).contains(7)) println(BloomFilter[Int](100).get.add(5).add(7).contains(6)) } }
code/data_structures/src/hashs/bloom_filter/bloom_filter.swift
public class BloomFilter<T> { private var array: [Bool] private var hashFunctions: [(T) -> Int] public init(size: Int = 1024, hashFunctions: [(T) -> Int]) { self.array = [Bool](repeating: false, count: size) self.hashFunctions = hashFunctions } private func computeHashes(_ value: T) -> [Int] { return hashFunctions.map { hashFunc in abs(hashFunc(value) % array.count) } } public func insert(_ element: T) { for hashValue in computeHashes(element) { array[hashValue] = true } } public func insert(_ values: [T]) { for value in values { insert(value) } } public func query(_ value: T) -> Bool { let hashValues = computeHashes(value) let results = hashValues.map { hashValue in array[hashValue] } let exists = results.reduce(true, { $0 && $1 }) return exists } public func isEmpty() -> Bool { return array.reduce(true) { prev, next in prev && !next } } }
code/data_structures/src/hashs/hash_table/README.md
# Definiton In computing, a hash table (hash map) is a data structure which implements an associative array abstract data type, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.</br> Ideally, the hash function will assign each key to a unique bucket, but most hash table designs employ an imperfect hash function, which might cause hash collisions where the hash function generates the same index for more than one key. Such collisions must be accommodated in some way.</br> In many situations, hash tables turn out to be more efficient than search trees or any other table lookup structure. # Further Reading https://en.wikipedia.org/wiki/Hash_table
code/data_structures/src/hashs/hash_table/double_hashing.c
// Part of Cosmos by OpenGenus Foundation #include<stdio.h> int hash_fn(int k, int i) { int h1,h2; h1 = k % 9; h2 = k % 8; return ((h1 + (i*h2))% 9); } void insert(int arr[]) { int k,i=1,id; printf("Enter the element \n"); scanf("%d",&k); id = k % 9; while(arr[id]!=-1) { id = hash_fn(k,i); i++; } arr[id] = k; } void search(int arr[]) { int q; printf("Enter query\n"); scanf("%d",&q); int id = q % 9 , i; for(i=0;i<9;i++) { if(arr[id] == q) { printf("Found\n"); break; } } printf("Not Found\n"); } void display(int arr[]) { int i ; for (i=0;i<9;i++) { printf("%d ",arr[i]); } printf("\n"); } int main() { int arr[9],i; for(i =0;i<9;i++) { arr[i] = -1; } for(i=0;i<9;i++) { insert(arr); } display(arr); search(arr); }
code/data_structures/src/hashs/hash_table/hash_table.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> // Part of Cosmos by OpenGenus Foundation #define SIZE 20 struct DataItem { int data; int key; }; struct DataItem* hashArray[SIZE]; struct DataItem* dummyItem; struct DataItem* item; int hashCode(int key) { return key % SIZE; } struct DataItem *search(int key) { //get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex] != NULL) { if(hashArray[hashIndex]->key == key) return hashArray[hashIndex]; //go to next cell ++hashIndex; //wrap around the table hashIndex %= SIZE; } return NULL; } void insert(int key,int data) { struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); item->data = data; item->key = key; //get the hash int hashIndex = hashCode(key); //move in array until an empty or deleted cell while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { //go to next cell ++hashIndex; //wrap around the table hashIndex %= SIZE; } hashArray[hashIndex] = item; } struct DataItem* delete(struct DataItem* item) { int key = item->key; //get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex] != NULL) { if(hashArray[hashIndex]->key == key) { struct DataItem* temp = hashArray[hashIndex]; //assign a dummy item at deleted position hashArray[hashIndex] = dummyItem; return temp; } //go to next cell ++hashIndex; //wrap around the table hashIndex %= SIZE; } return NULL; } void display() { int i = 0; for(i = 0; i<SIZE; i++) { if(hashArray[i] != NULL) printf(" (%d,%d)",hashArray[i]->key,hashArray[i]->data); else printf(" ~~ "); } printf("\n"); } int main() { dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); dummyItem->data = -1; dummyItem->key = -1; insert(1, 20); insert(2, 70); insert(42, 80); insert(4, 25); insert(12, 44); insert(14, 32); insert(17, 11); insert(13, 78); insert(37, 97); display(); item = search(37); if(item != NULL) { printf("Element found: %d\n", item->data); } else { printf("Element not found\n"); } delete(item); item = search(37); if(item != NULL) { printf("Element found: %d\n", item->data); } else { printf("Element not found\n"); } }
code/data_structures/src/hashs/hash_table/hash_table.cpp
/* * Part of Cosmos by OpenGenus Foundation * * hash_table synopsis * * template<typename _Tp, typename _HashFunc = std::hash<_Tp> > * class hash_table { * public: * typedef _Tp value_type; * typedef decltype (_HashFunc ().operator()(_Tp())) key_type; * typedef std::map<key_type, value_type> container_type; * typedef typename container_type::const_iterator const_iterator; * typedef typename container_type::size_type size_type; * * // Initialize your data structure here. * hash_table() :_container({}) {} * * // Inserts a value to the set. Returns true if the set did not already contain the specified * element. * std::pair<const_iterator, bool> insert(const _Tp val); * * template<typename _InputIter> * void insert(_InputIter first, _InputIter last); * * void insert(std::initializer_list<_Tp> init_list); * * // Removes a value from the set. Returns true if the set contained the specified element. * const_iterator erase(const _Tp val); * * const_iterator erase(const_iterator pos); * * // Find a value from the set. Returns true if the set contained the specified element. * * const_iterator find(const _Tp val) const; * * const_iterator end() const; * * bool empty() const; * * size_type size() const; * * private: * container_type _container; * * key_type hash(const value_type &val) const; * * template<typename _InputIter> * void _insert(_InputIter first, _InputIter last, std::input_iterator_tag); * }; */ #include <map> template<typename _Tp, typename _HashFunc = std::hash<_Tp>> class hash_table { public: typedef _Tp value_type; typedef decltype (_HashFunc ().operator()(_Tp())) key_type; typedef std::map<key_type, value_type> container_type; typedef typename container_type::const_iterator const_iterator; typedef typename container_type::size_type size_type; /** Initialize your data structure here. */ hash_table() : _container({}) { } /** Inserts a value to the set. Returns true if the set did not already contain the specified * element. */ std::pair<const_iterator, bool> insert(const _Tp val) { key_type key = hash(val); if (_container.find(key) == _container.end()) { _container.insert(std::make_pair(key, val)); return make_pair(_container.find(key), true); } return make_pair(_container.end(), false); } template<typename _InputIter> void insert(_InputIter first, _InputIter last) { _insert(first, last, typename std::iterator_traits<_InputIter>::iterator_category()); } void insert(std::initializer_list<_Tp> init_list) { insert(init_list.begin(), init_list.end()); } /** Removes a value from the set. Returns true if the set contained the specified element. */ const_iterator erase(const _Tp val) { const_iterator it = find(val); if (it != end()) return erase(it); return end(); } const_iterator erase(const_iterator pos) { return _container.erase(pos); } /** Find a value from the set. Returns true if the set contained the specified element. */ const_iterator find(const _Tp val) { key_type key = hash(val); return _container.find(key); } const_iterator find(const _Tp val) const { key_type key = hash(val); return _container.find(key); } const_iterator end() const { return _container.end(); } bool empty() const { return _container.empty(); } size_type size() const { return _container.size(); } private: container_type _container; key_type hash(const value_type &val) const { return _HashFunc()(val); } template<typename _InputIter> void _insert(_InputIter first, _InputIter last, std::input_iterator_tag) { _InputIter pos = first; while (pos != last) insert(*pos++); } }; /* * // for test * * // a user-defined hash function * template<typename _Tp> * struct MyHash { * // hash by C++ boost * // phi = (1 + sqrt(5)) / 2 * // 2^32 / phi = 0x9e3779b9 * void hash(std::size_t &seed, const _Tp &i) const * { * seed ^= std::hash<_Tp>()(i) + 0x87654321 * (seed << 1) + (seed >> 2); * seed <<= seed % 6789; * } * * std::size_t operator()(const _Tp &d) const * { * std::size_t seed = 1234; * hash(seed, d); * * return seed; * } * }; * #include <iostream> #include <vector> * using namespace std; * * int main() { * hash_table<int, MyHash<int> > ht; * * // test find * if (ht.find(9) != ht.end()) * cout << __LINE__ << " error\n"; * * // test insert(1) * if (!ht.insert(3).second) // return true * cout << __LINE__ << " error\n"; * * if (ht.insert(3).second) // return false * cout << __LINE__ << " error\n"; * * // test insert(2) * vector<int> input{10, 11, 12}; * ht.insert(input.begin(), input.end()); * if (ht.find(10) == ht.end()) * cout << __LINE__ << " error\n"; * if (ht.find(11) == ht.end()) * cout << __LINE__ << " error\n"; * if (ht.find(12) == ht.end()) * cout << __LINE__ << " error\n"; * * // test insert(3) * ht.insert({13, 14, 15, 16}); * * // test erase(1) * ht.erase(13); * * // test erase(2) * auto it = ht.find(14); * ht.erase(it); * * // test empty * if (ht.empty()) * cout << __LINE__ << " error\n"; * * // test size * if (ht.size() != 6) * cout << __LINE__ << " error\n"; * * return 0; * } * * // */
code/data_structures/src/hashs/hash_table/hash_table.cs
using System; using System.Collections; // namespace for hashtable using System.Linq; using System.Text; using System.Threading.Tasks; /* * Part of Cosmos by OpenGenus Foundation' * * The Hashtable class represents a collection of key-and-value pairs that are organized * based on the hash code of the key. It uses the key to access the elements in the collection. * */ namespace hashtables { sealed class hTable // a class { static int key; // key of the hastable public bool uniqueness { get; set; } // setting to check if allow uniqueness or not Hashtable hashtable = new Hashtable(); internal void add(string value) { if(uniqueness) { if(hashtable.ContainsValue(value)) { Console.WriteLine("Entry exists"); } else { hashtable.Add(++key,value); } } else { hashtable.Add(++key, value); } } internal void delete(int key) { if (hashtable.ContainsKey(key)) { Console.WriteLine("Deleted value : " + hashtable[key].ToString()); hashtable.Remove(key); } else { Console.WriteLine("Key not found"); } } internal void show() { foreach(var key in hashtable.Keys) { Console.WriteLine(key.ToString() + " : " + hashtable[key]); } } } class Program { static void Main(string[] args) { hTable obj = new hTable(); // i want uniqueness therefore making property true obj.uniqueness = true; // adding 3 values Console.WriteLine("ADDING EXAMPLE"); obj.add("terabyte"); obj.add("sandysingh"); obj.add("adichat"); // adding terabyte again to see the exists message Console.WriteLine("ADDING 'terabyte' AGAIN"); obj.add("terabyte"); // showing all original Console.WriteLine("Original Table"); obj.show(); // removing value at key = 2 Console.WriteLine("Deleting value"); obj.delete(2); // showing all new Console.WriteLine("New Table"); obj.show(); Console.ReadKey(); // in ordr to pause the program } } }
code/data_structures/src/hashs/hash_table/hash_table.go
package main import ( "errors" "fmt" "container/list" ) var ( ErrKeyNotFound = errors.New("key not found") ) type Item struct { key int value interface{} } type Hashtable struct{ size int data []*list.List } func (h *Hashtable) Insert(key int, value interface{}) { item := &Item{key: key, value: value} hashed := key % h.size l := h.data[hashed] if l == nil { l = list.New() h.data[hashed] = l } for elem := l.Front(); elem != nil; elem = elem.Next() { // If found the element -> update i, _ := elem.Value.(*Item) if i.key == item.key { i.value = value return } } l.PushFront(item) return } func (h *Hashtable) Get(key int) (interface{}, error) { hashed := key % h.size l := h.data[hashed] if l == nil { return nil, ErrKeyNotFound } for elem := l.Front(); elem != nil; elem = elem.Next() { item := elem.Value.(*Item) if item.key == key { return item.value, nil } } return nil, ErrKeyNotFound } func NewHashtable(size int) *Hashtable { return &Hashtable{ size: size, data: make([]*list.List, size), } } func main() { h := NewHashtable(10) h.Insert(1, "abc") value, _ := h.Get(1) fmt.Printf("h[1] = %s\n", value) // Print "abc" h.Insert(11, "def") value, _ = h.Get(11) fmt.Printf("h[11] = %s\n", value) // Print "def" value, err := h.Get(2) fmt.Printf("Err = %#v\n", err) // ErrKeyNotFound }
code/data_structures/src/hashs/hash_table/hash_table.java
// Part of Cosmos by OpenGenus Foundation public class HashTable<K, V> { private class HTPair { K key; V value; public HTPair(K key, V value) { this.key = key; this.value = value; } public boolean equals(Object other) { HTPair op = (HTPair) other; return this.key.equals(op.key); } public String toString() { return "{" + this.key + "->" + this.value + "}"; } } private LinkedList<HTPair>[] bucketArray; private int size; public static final int DEFAULT_CAPACITY = 5; public HashTable() { this(DEFAULT_CAPACITY); } public HashTable(int capacity) { this.bucketArray = (LinkedList<HTPair>[]) new LinkedList[capacity]; this.size = 0; } public int size() { return this.size; } private int HashFunction(K key) { int hc = key.hashCode(); hc = Math.abs(hc); int bi = hc % this.bucketArray.length; return bi; } public void put(K key, V value) throws Exception { int bi = HashFunction(key); HTPair data = new HTPair(key, value); if (this.bucketArray[bi] == null) { LinkedList<HTPair> bucket = new LinkedList<>(); bucket.addLast(data); this.size++; this.bucketArray[bi] = bucket; } else { int foundAt = this.bucketArray[bi].find(data); if (foundAt == -1) { this.bucketArray[bi].addLast(data); this.size++; } else { HTPair obj = this.bucketArray[bi].getAt(foundAt); obj.value = value; this.size++; } } double lambda = (this.size) * 1.0; lambda = this.size / this.bucketArray.length; if (lambda > 0.75) { rehash(); } } public void display() { for (LinkedList<HTPair> list : this.bucketArray) { if (list != null && !list.isEmpty()) { list.display(); } else { System.out.println("NULL"); } } } public V get(K key) throws Exception { int index = this.HashFunction(key); LinkedList<HTPair> list = this.bucketArray[index]; HTPair ptf = new HTPair(key, null); if (list == null) { return null; } else { int findAt = list.find(ptf); if (findAt == -1) { return null; } else { HTPair pair = list.getAt(findAt); return pair.value; } } } public V remove(K key) throws Exception { int index = this.HashFunction(key); LinkedList<HTPair> list = this.bucketArray[index]; HTPair ptf = new HTPair(key, null); if (list == null) { return null; } else { int findAt = list.find(ptf); if (findAt == -1) { return null; } else { HTPair pair = list.getAt(findAt); list.removeAt(findAt); this.size--; return pair.value; } } } public void rehash() throws Exception { LinkedList<HTPair>[] oba = this.bucketArray; this.bucketArray = (LinkedList<HTPair>[]) new LinkedList[2 * oba.length]; this.size = 0; for (LinkedList<HTPair> ob : oba) { while (ob != null && !ob.isEmpty()) { HTPair pair = ob.removeFirst(); this.put(pair.key, pair.value); } } } }
code/data_structures/src/hashs/hash_table/hash_table.js
var HashTable = function() { this._storage = []; this._count = 0; this._limit = 8; }; HashTable.prototype.insert = function(key, value) { //create an index for our storage location by passing it through our hashing function var index = this.hashFunc(key, this._limit); //retrieve the bucket at this particular index in our storage, if one exists //[[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ] [ [k,v] ] ] var bucket = this._storage[index]; //does a bucket exist or do we get undefined when trying to retrieve said index? if (!bucket) { //create the bucket var bucket = []; //insert the bucket into our hashTable this._storage[index] = bucket; } var override = false; //now iterate through our bucket to see if there are any conflicting //key value pairs within our bucket. If there are any, override them. for (var i = 0; i < bucket.length; i++) { var tuple = bucket[i]; if (tuple[0] === key) { //overide value stored at this key tuple[1] = value; override = true; } } if (!override) { //create a new tuple in our bucket //note that this could either be the new empty bucket we created above //or a bucket with other tupules with keys that are different than //the key of the tuple we are inserting. These tupules are in the same //bucket because their keys all equate to the same numeric index when //passing through our hash function. bucket.push([key, value]); this._count++; //now that we've added our new key/val pair to our storage //let's check to see if we need to resize our storage if (this._count > this._limit * 0.75) { this.resize(this._limit * 2); } } return this; }; HashTable.prototype.remove = function(key) { var index = this.hashFunc(key, this._limit); var bucket = this._storage[index]; if (!bucket) { return null; } //iterate over the bucket for (var i = 0; i < bucket.length; i++) { var tuple = bucket[i]; //check to see if key is inside bucket if (tuple[0] === key) { //if it is, get rid of this tuple bucket.splice(i, 1); this._count--; if (this._count < this._limit * 0.25) { this._resize(this._limit / 2); } return tuple[1]; } } }; HashTable.prototype.retrieve = function(key) { var index = this.hashFunc(key, this._limit); var bucket = this._storage[index]; if (!bucket) { return null; } for (var i = 0; i < bucket.length; i++) { var tuple = bucket[i]; if (tuple[0] === key) { return tuple[1]; } } return null; }; HashTable.prototype.hashFunc = function(str, max) { var hash = 0; for (var i = 0; i < str.length; i++) { var letter = str[i]; hash = (hash << 5) + letter.charCodeAt(0); hash = (hash & hash) % max; } return hash; }; HashTable.prototype.resize = function(newLimit) { var oldStorage = this._storage; this._limit = newLimit; this._count = 0; this._storage = []; oldStorage.forEach( function(bucket) { if (!bucket) { return; } for (var i = 0; i < bucket.length; i++) { var tuple = bucket[i]; this.insert(tuple[0], tuple[1]); } }.bind(this) ); }; HashTable.prototype.retrieveAll = function() { console.log(this._storage); };
code/data_structures/src/hashs/hash_table/hash_table.py
""" Hash Table implementation in Python using linear probing. This code is based on the c/c++ implementation that I used to study hashing. https://github.com/jwasham/practice-c/tree/master/hash_table """ # Maximum number of elements. MAX_SIZE = 8 # Small size helps in checking for collission response # Key-Value pairs class HashObject(object): def get_dummy_key(): return "<Dummy>" def get_null_key(): return "<Null>" def __init__(self): self.key_ = None self.value_ = None def set_key(self, key): self.key_ = key def set_value(self, value): self.value_ = value def get_key(self): return self.key_ def get_value(self): return self.value_ def set_as_dummy(self): self.set_key(HashObject.get_dummy_key()) self.set_value("") # HashTable class class HashTable(object): # init method def __init__(self, n): self.size_ = n self.data_ = [HashObject() for _ in range(n)] # print method def __str__(self): output = "" for i in range(self.size_): if self.data_[i].get_key() != None: output += ( str(i) + " => " + str( self.data_[i].get_key() + " : " + str(self.data_[i].get_value()) + "\n" ) ) return output # hash method def s_hash(self, key): hash_val = 0 for i in key: hash_val = (hash_val * 31) + ord(i) return hash_val % self.size_ # insert a key-value pair into the table def add(self, key_val_pair): index = self.s_hash(key_val_pair.get_key()) original_index = index found = False dummy_index = -1 while self.data_[index].get_key() != None: if self.data_[index].get_key() == key_val_pair.get_key(): found = True break if ( dummy_index == -1 and self.data_[index].get_key() == HashObject.get_dummy_key() ): dummy_index = index index = (index + 1) % self.size_ if index == original_index: return if not found and dummy_index != -1: index = dummy_index self.data_[index].set_key(key_val_pair.get_key()) self.data_[index].set_value(key_val_pair.get_value()) # check whether the key eists in the table def exists(self, key): index = self.s_hash(key) original_index = index while self.data_[index].get_key() != None: if self.data_[index].get_key() == key: return True index = (index + 1) % self.size_ if index == original_index: return False return False # Get value corresponding to the key def get(self, key): index = self.s_hash(key) original_index = index while self.data_[index].get_key() != None: if self.data_[index].get_key() == key: return self.data_[index].get_value() index = (index + 1) % self.size_ if index == original_index: return HashObject.get_null_key() return HashObject.get_null_key() # Remove the entry with the given key def remove(self, key): index = self.s_hash(key) original_index = index while self.data_[index].get_key() != None: if self.data_[index].get_key() == key: self.data_[index].set_as_dummy() break index = (index + 1) % self.size_ if index == original_index: break if __name__ == "__main__": state = HashObject() table = HashTable(MAX_SIZE) state.set_key("Bihar") state.set_value("Patna") table.add(state) state.set_key("Jharkhand") state.set_value("Ranchi") table.add(state) state.set_key("Kerala") state.set_value("Thiruvanantpuram") table.add(state) state.set_key("WB") state.set_value("Kolkata") table.add(state) print(table) table.remove("Jharkhand") table.remove("WB") print(table) state.set_key("WB") state.set_value("Kolkata") table.add(state) print(table)
code/data_structures/src/hashs/hash_table/hash_table.rs
use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; use std::fmt; trait HashFunc { type Key; type Value; fn new(key: Self::Key, value: Self::Value) -> Self; fn get_value(&self) -> &Self::Value; fn get_key(&self) -> &Self::Key; } struct HashTable<K, V> { list: Vec<Vec<HashPair<V, K>>>, mindex: u64, size: u64, } impl<K, V> HashTable<K, V> where K: Hash + PartialEq + fmt::Display, V: fmt::Display, { fn new(index: u64) -> Self { let mut empty_vec = Vec::new(); for _ in 0..index { empty_vec.push(Vec::new()); } HashTable { list: empty_vec, size: 0, mindex: index, } } fn hash(&self, key: &K) -> u64 { let mut hasher = DefaultHasher::new(); key.hash(&mut hasher); hasher.finish() % self.mindex } fn get(&self, key: K) -> Option<&V> { let index = self.hash(&key); if let Some(list) = self.list.get(index as usize) { if let Some(ele) = list.iter().find(|x| *x.get_key() == key) { Some(ele.get_value()) } else { None } } else { None } } fn put(&mut self, key: K, value: V) { let index = self.hash(&key); if let Some(lin_list) = self.list.get_mut(index as usize) { let insert_value = HashPair::new(key, value); if let Some(index) = lin_list.iter().position( |x| *x.get_key() == insert_value.key, ) { lin_list.remove(index); } lin_list.push(insert_value); self.size += 1; } } fn remove(&mut self, key: K) { let index = self.hash(&key); if let Some(lin_list) = self.list.get_mut(index as usize) { lin_list.retain(|x| *x.get_key() != key); self.size -= 1; } } fn size(&self) -> u64 { self.size } fn print(&self) { for index in 0..self.mindex { if let Some(lin_list) = self.list.get(index as usize) { for inner_index in 0..lin_list.len() { print!("{} ", lin_list.get(inner_index).unwrap()); } } } println!(); } } struct HashPair<T, K> { key: K, value: T, } impl<T, K> fmt::Display for HashPair<T, K> where T: fmt::Display, K: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.key, self.value) } } impl<T, K> HashFunc for HashPair<T, K> { type Key = K; type Value = T; fn get_value(&self) -> &Self::Value { &self.value } fn get_key(&self) -> &Self::Key { &self.key } fn new(key: Self::Key, value: Self::Value) -> Self { HashPair { key: key, value: value, } } } const MINDEX: u64 = 128; fn main() { let mut test = HashTable::new(MINDEX); test.put("hello", "bye"); test.put("what's up", "dude"); test.remove("hell"); test.print(); }
code/data_structures/src/hashs/hash_table/hash_table.swift
class HashElement<T: Hashable, U> { var key: T var value: U? init(key: T, value: U?) { self.key = key self.value = value } } struct HashTable<Key: Hashable, Value: CustomStringConvertible> { private typealias Element = HashElement<Key, Value> private typealias Bucket = [Element] private var buckets: [Bucket] /// Number of key-value pairs in the hash table. private(set) public var count = 0 /// A Boolean value that indicates whether the hash table is empty. public var isEmpty: Bool { return count == 0 } /// A string that represents the contents of the hash table. public var description: String { let pairs = buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } } return pairs.joined(separator: ", ") } /// A string that represents the contents of the hash table, suitable for debugging. public var debugDescription: String { var str = "" for (i, bucket) in buckets.enumerated() { let pairs = bucket.map { e in "\(e.key) = \(e.value)" } str += "bucket \(i): " + pairs.joined(separator: ", ") + "\n" } return str } /// Initialise hash table with the given capacity. /// /// - Parameter capacity: hash table capacity. init(capacity: Int) { assert(capacity > 0) buckets = Array<Bucket>(repeatElement([], count: capacity)) } /// Returns an array index for a given key private func index(forKey key: Key) -> Int { return abs(key.hashValue) % buckets.count } /// Returns the value for the given key func value(for key: Key) -> Value? { let index = self.index(forKey: key) for element in buckets[index] { if element.key == key { return element.value } } return nil // key not in the hash table } /// Accesses element's value (get,set) in hash table for a given key. subscript(key: Key) -> Value? { get { return value(for: key) } set { if let value = newValue { updateValue(value, forKey: key) } else { removeValue(for: key) } } } /// Updates element's value in the hash table for the given key, or adds a new element if the key doesn't exists. @discardableResult mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { let itemIndex = self.index(forKey: key) for (i, element) in buckets[itemIndex].enumerated() { if element.key == key { let oldValue = element.value buckets[itemIndex][i].value = value return oldValue } } buckets[itemIndex].append(HashElement(key: key, value: value)) // Adding element to the chain. count += 1 return nil } /// Removes element from the hash table for a given key. @discardableResult mutating func removeValue(for key: Key) -> Value? { let index = self.index(forKey: key) // Search and destroy for (i, element) in buckets[index].enumerated() { if element.key == key { buckets[index].remove(at: i) count -= 1 return element.value } } return nil // key not in the hash table } /// Removes all elements from the hash table. public mutating func removeAll() { buckets = Array<Bucket>(repeatElement(nil, count: buckets.count)) count = 0 } }
code/data_structures/src/list/Queue_using_Linked_list/Queue_using_Linked_List.c
#include<stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node * rear=0; struct node * front=0; //insertion void enqueue(int x) { struct node * temp=0; temp=(struct node *)malloc(sizeof(struct node)); if(temp==0) { printf("\nQueue Overflow"); return; } temp->data=x; temp->next=0; if(front==0 && rear==0) { front=temp; rear=temp; } else { rear->next=temp; rear=temp; } } //deletion void dequeue() { if(front==0 && rear==0) { printf("\nQueue underflow"); return; } struct node * temp=front; temp=(struct node *)malloc(sizeof(struct node)); if(front==rear) { front=0; rear=0; } else { front=front->next; free(temp); } } //printing the elements void print() { if(front==0 && rear==0) { printf("\nQueue underflow"); return; } printf("\nQueue: "); struct node *temp = front; while(temp!=0) { printf("%d ",temp->data); temp=temp->next; } } int main() { print(); enqueue(10); print(); enqueue(20); enqueue(30); print(); dequeue(); dequeue(); print(); dequeue(); return 0; }
code/data_structures/src/list/README.md
# Linked List A linked list is a data structure containing a series of data that's linked together. Each node of a linked list contains a piece of data and a link to the next node, as shown in the diagram below: ![Singly linked list diagram](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Singly-linked-list.svg/408px-Singly-linked-list.svg.png) Image credit: `By Lasindi - Own work, Public Domain, https://commons.wikimedia.org/w/index.php?curid=2245162` ## Types of Linked Lists There are several types of linked lists. The most common ones are: ### Singly linked list The simplest type. Each node has a data field and a link to the next node, with the last node's link being empty or pointing to `null`. ### Double linked list ![Doubly linked list diagram](https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Doubly-linked-list.svg/610px-Doubly-linked-list.svg.png) Image credit: `By Lasindi, Public Domain, https://commons.wikimedia.org/wiki/File:Doubly-linked-list.svg` Each node of a doubly linked list contains, in addition to the data field and a link to the next code, a link to the previous node. ## Circularly linked list ![Circularly linked list diagram](https://upload.wikimedia.org/wikipedia/commons/thumb/d/df/Circularly-linked-list.svg/350px-Circularly-linked-list.svg.png) Image credit: `By Lasindi, Public Domain, https://commons.wikimedia.org/wiki/File:Circularly-linked-list.svg` A singly linked list, except that the last item links back to the first item, as opposed to a singly linked list which links to nothing or `null`. ## Sources and more detailed information: - https://en.wikipedia.org/wiki/Linked_list --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/data_structures/src/list/circular_linked_list/circular_linked_list.c
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Node node; void display(node *tail); node *insert_at_end(node *tail); node *insert_at_front(node *tail); node *delete_at_begin(node *tail); node *delete_at_end(node *tail); struct Node { int Data; struct Node *next; }; /*Traversing circular linked list*/ node *random_list(node *tail) { int t; printf("Enter number of elements: "); scanf("%d",&t); free(tail); tail=(node*)malloc(sizeof(node)); node* head=tail; tail->Data=rand()%20 +1; tail->next=tail; for (int i = 0; i < t-1; i++) { node* new=(node*)malloc(sizeof(node)); new->Data=rand()%20 + 1; tail->next=new; new->next=head; tail=new; } return head; } void display(node *tail) { node *root, *ptr; if (tail == NULL) printf("\nList is empty\n\n"); else { root = tail->next; ptr = root; while (ptr != tail) { printf("%d ", ptr->Data); ptr = ptr->next; } printf("%d\n", ptr->Data); } } /*Inserting node at front of the list*/ node * insert_at_front(node *tail) { /*Creating new node*/ node *temp = (node *)malloc(sizeof(node)); printf("\nEnter Data:"); scanf("%d", &temp->Data); /*Check initial condition for list ,it is empty or not*/ if (tail == NULL) { tail = temp; tail->next = temp; } else { temp->next = tail->next; tail->next = temp; } return (tail); } /*Inserting node at the end of list*/ node * insert_at_end(node *tail) { node *temp = (node *)malloc(sizeof(node)); printf("\nEnter Data:"); scanf("%d", &temp->Data); if (tail == NULL) { tail = temp; tail->next = temp; } else { node *root; root = tail->next; tail->next = temp; temp->next = root; tail = temp; } return (tail); } /*Deleting node at the front of list*/ node * delete_at_begin(node *tail) { if (tail == NULL) printf("\nList is Empty\n\n"); else { if (tail->next == tail) { free(tail); tail = NULL; } else { node *root, *ptr; ptr = root = tail->next; root = root->next; tail->next = root; free(ptr); } } return (tail); } /*Deleting node at the end of list*/ node * delete_at_end(node *tail) { if (tail == NULL) printf("\nList is empty\n\n"); else { if (tail->next == tail) { free(tail); tail = NULL; } else { node *root; root = tail->next; while (root->next != tail) { root = root->next; } root->next = tail->next; free(tail); tail = root; } } return (tail); } int main(int argc, char *argv[]) { /*Declaring tail pointer to maintain last node address*/ srand(time(0)); node *tail = NULL; int choice; while (1) { /*We can also write print function outside of while loop */ printf("1.Create a random list\n2.Insert at front\n3.Insert at end \n4.Display\n5.Delete from front\n6.Delete from End\n7.Exit\nEnter choice:"); scanf("%d", &choice); switch (choice) { case 1: tail = random_list(tail); break; case 2: tail = insert_at_front(tail); break; case 3: tail = insert_at_end(tail); break; case 4: display(tail); break; case 5: tail = delete_at_begin(tail); break; case 6: tail = delete_at_end(tail); break; case 7: return (0); } } }
code/data_structures/src/list/circular_linked_list/circular_linked_list.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; int main() { struct node { int info; node *next; }*ptr, *head, *start; int c = 1, data; ptr = new node; ptr->next = NULL; start = head = ptr; while (c < 3 && c > 0) { cout << "1.Insert\n2.Link List\n"; cin >> c; switch (c){ case 1: cout << "Enter Data\n"; cin >> data; ptr = new node; ptr->next = start; ptr->info = data; head->next = ptr; head = ptr; break; case 2: ptr = start->next; while (ptr != start && ptr != NULL) { cout << ptr->info << "->"; ptr = ptr->next; } cout << "\n"; break; default: cout << "Wrong Choice\nExiting...\n"; } } return 0; }
code/data_structures/src/list/circular_linked_list/circular_linked_list.java
import java.util.Scanner; // Part of Cosmos by OpenGenus Foundation public class CircularLinkedList { Node head, tail; // Node Class class Node { int value; Node next; public Node(int value, Node next) { this.value = value; this.next = next; } } // Manipulation Methods public void Add(int value) { Node n = new Node(value, head); if (head == null) { head = n; tail = n; n.next = n; } else { tail.next = n; tail = n; } } public void Remove(int value) { Node aux = head; Node prev = tail; boolean found = false; // Find the node with the value if (aux == null) return; if (aux == head && aux.value == value) { found = true; } else { prev = aux; aux = aux.next; while (aux != head) { if (aux.value == value) { found = true; break; } prev = aux; aux = aux.next; } } // If found, remove it if (!found) return; if (aux == head && aux == tail) { head = tail = null; } else { if (aux == head) head = aux.next; if (aux == tail) tail = prev; prev.next = aux.next; } } public void Print() { if (head == null) return; System.out.print(head.value + " "); Node aux = head.next; while (aux != head) { System.out.print(aux.value + " "); aux = aux.next; } System.out.println(); System.out.println("HEAD is " + head.value); System.out.println("TAIL is " + tail.value); } // Example Usage public static void main(String[] args) { int selection = 0; Scanner input = new Scanner(System.in); CircularLinkedList list = new CircularLinkedList(); do { System.out.print("1. Insert\n2. Remove\n3. Print\n> "); selection = input.nextInt(); if (selection == 1) { System.out.print("Enter Value to Insert: "); int value = input.nextInt(); list.Add(value); list.Print(); System.out.print("\n"); } else if (selection == 2) { System.out.print("Enter Value to Remove: "); int value = input.nextInt(); list.Remove(value); list.Print(); System.out.println("\n"); } else if (selection == 3) { list.Print(); System.out.println("\n"); } else { System.out.println("Invalid Selection. Exiting"); } } while (selection > 0 && selection < 4); input.close(); } }
code/data_structures/src/list/circular_linked_list/circular_linked_list.py
class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None class CircularLinkedList: # Constructor to create a empty circular linked list def __init__(self): self.head = None # Function to insert a node at the beginning of a # circular linked list def push(self, data): ptr1 = Node(data) temp = self.head ptr1.next = self.head # If linked list is not None then set the next of # last node if self.head is not None: while temp.next != self.head: temp = temp.next temp.next = ptr1 else: ptr1.next = ptr1 # For the first node self.head = ptr1 # Function to print nodes in a given circular linked list def printList(self): temp = self.head if self.head is not None: while True: print("%d" % (temp.data), end=" ") temp = temp.next if temp == self.head: break # Driver program to test above function # Initialize list as empty cllist = CircularLinkedList() # Created linked list will be 11->2->56->12 cllist.push(12) cllist.push(56) cllist.push(2) cllist.push(11) print("Contents of circular Linked List") cllist.printList()
code/data_structures/src/list/circular_linked_list/operations/FloydAlgo_circular_ll.cpp
#include <iostream> using namespace std; struct node{ int data; struct node* next; }; bool isCircular(node *head) { //fast ptr is ahead of slow pointer node* slow,*fast; slow=head; fast=head->next; //if linked list is empty it returns true as its entirely null. if(head==NULL) return true; while(true) { //fast ptr traverses quickly so If its not circular then it reaches or points to null. if(fast==NULL||fast->next==NULL) { return false; } //when circular fast meets or points to slow pointer while traversing else if(slow==fast||fast->next==slow) { return true; } //for moving forward through linked list. else { slow=slow->next; //fast traverses way ahead so it distinguishes loops out of circular list. fast=fast->next->next; } } } node *newNode(int data){ struct node *temp=new node; temp->data=data; temp->next=NULL; } int main() { struct node* head=newNode(1); head->next=newNode(2); head->next->next=newNode(12); head->next->next->next=newNode(122); head->next->next->next->next=head; if(isCircular(head)) cout<<"yes"<<endl; else cout<<"no"<<endl; struct node* head1=newNode(1); head1->next=newNode(2); head1->next->next=newNode(3); head1->next->next->next=newNode(7); if(isCircular(head1)) cout<<"yes"; else cout<<"no"; return 0; }
code/data_structures/src/list/circular_linked_list/operations/has_loop.py
import collections class LinkedList(collections.Iterable): class Node(object): def __init__(self, data, next=None): super(LinkedList.Node, self).__init__() self.data = data self.next = next class LinkedListIterator(collections.Iterator): def __init__(self, head): self._cur = head def __iter__(self): return self def next(self): if self._cur is None: raise StopIteration retval = self._cur self._cur = self._cur.next return retval def __init__(self): super(LinkedList, self).__init__() self.head = None def __iter__(self): it = LinkedList.LinkedListIterator(self.head) return iter(it) def add(self, data): # add new node to head of list new = LinkedList.Node(data, self.head) self.head = new return new def add_node(self, node): node.next = self.head self.head = node return node def rm(self, node): # del node from list it = iter(self) prev = self.head try: while True: n = it.next() if n is node: if n is self.head: self.head = self.head.next else: prev.next = n.next return prev = n except StopIteration: raise KeyError def has_loop(self): class Skip2Iterator(LinkedList.LinkedListIterator): def next(self): super(Skip2Iterator, self).next() return super(Skip2Iterator, self).next() it = LinkedList.LinkedListIterator(self.head) it2 = Skip2Iterator(self.head) try: while True: n1 = it.next() n2 = it2.next() if n1 is n2: return True except StopIteration: return False
code/data_structures/src/list/circular_linked_list/operations/is_circular.py
# uses try block so dont have to check if reached the end, provides faster runtime. credit-leetcode def is_circular(self, head): """ function checks if a link list has a cycle or not """ try: slow = head fast = head.next while slow is not fast: slow = slow.next fast = fast.next.next return True except: return False
code/data_structures/src/list/circular_linked_list/operations/is_circular_linked_list.cpp
#include <iostream> using namespace std; //node structure struct node{ int data; struct node* next; }; //function to find the circular linked list. bool isCircular(node *head){ node *temp=head; while(temp!=NULL) { //if temp points to head then it has completed a circle,thus a circular linked list. if(temp->next==head) return true; temp=temp->next; } return false; } //function for inserting new nodes. node *newNode(int data){ struct node *temp=new node; temp->data=data; temp->next=NULL; } int main() { //first case struct node* head=newNode(1); head->next=newNode(2); head->next->next=newNode(3); head->next->next->next=newNode(4); head->next->next->next->next=head; if(isCircular(head)) cout<<"yes"<<endl; else cout<<"no"<<endl; //second case struct node* head1=newNode(1); head1->next=newNode(2); if(isCircular(head1)) cout<<"yes"; else cout<<"no"; return 0; }
code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "doubly_linked_list.h" dllist_t *dl_create() { dllist_t *l = (dllist_t *) calloc(1, sizeof(dllist_t)); return l; } int8_t dl_destroy(dllist_t **l) { if (*l == (dllist_t *) NULL) return ERR_NO_LIST; if ((*l)->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *p = (*l)->head; while (p != (node_t *) NULL) { (*l)->head = p->next; free(p); p = (*l)->head; } (*l)->tail = (node_t *) NULL; *l = (dllist_t *) NULL; return SUCCESS; } int8_t dl_insert_beginning(dllist_t *l, int32_t value) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; node_t *nn = (node_t *) calloc(1, sizeof(node_t)); if (nn == (node_t *) NULL) return ERR_MALLOC_FAIL; nn->id = l->tail_id++; nn->data = value; nn->prev = (node_t *) NULL; node_t *p = l->head; if (p == (node_t *) NULL) { l->tail = nn; } else { nn->next = p; p->prev = nn; } l->head = nn; l->len++; return SUCCESS; } int8_t dl_insert_tail(dllist_t *l, int32_t value) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; node_t *nn = (node_t *) calloc(1, sizeof(node_t)); if (nn == (node_t *) NULL) return ERR_MALLOC_FAIL; nn->id = l->tail_id++; nn->data = value; node_t *p = l->tail; if (l->head == (node_t *) NULL) { l->head = nn; l->tail = nn; } else { p->next = nn; nn->prev = p; l->tail = nn; } l->len++; return SUCCESS; } int8_t dl_insert_after(dllist_t *l, int32_t key, int32_t value) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; if (l->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *nn = (node_t *) calloc(1, sizeof(node_t)); if (nn == (node_t *) NULL) return ERR_MALLOC_FAIL; nn->id = l->tail_id++; nn->data = value; node_t *p = l->head; while (p != (node_t *) NULL) { if (p->data == key) { nn->next = p->next; p->next = nn; nn->prev = p; if (p == l->tail) { l->tail = nn; } break; } p = p->next; } return SUCCESS; } int8_t dl_insert_before(dllist_t *l, int32_t key, int32_t value) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; if (l->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *nn = (node_t *) calloc(1, sizeof(node_t)); if (nn == (node_t *) NULL) return ERR_MALLOC_FAIL; nn->id = l->tail_id++; nn->data = value; node_t *p = l->head; while (p != (node_t *) NULL) { if (p->data == key) { if (p == l->head) { l->head = nn; } else { p->prev->next = nn; } nn->next = p; nn->prev = p->prev; break; } p = p->next; } return SUCCESS; } int8_t dl_remove_beginning(dllist_t *l) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; if (l->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *p = l->head; l->head = p->next; p->next = (node_t *) NULL; free(p); l->len--; return SUCCESS; } int8_t dl_remove_tail(dllist_t *l) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; if (l->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *p = l->tail; if (p == l->head) { l->head = (node_t *) NULL; } else { p->prev->next = (node_t *) NULL; l->tail = p->prev; } free(p); l->len--; return SUCCESS; } int8_t dl_remove_next(dllist_t *l, int32_t key) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; if (l->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *p = l->head; node_t *r = (node_t *) NULL; while (p->next != (node_t *) NULL) { if (p->id == key) { r = p->next; if (r->next == (node_t *) NULL) { l->tail = p; p->next = (node_t *) NULL; } else { r->next->prev = p; p->next = r->next; } free(r); l->len--; r = (node_t *) NULL; break; } p = p->next; } return SUCCESS; } int8_t dl_remove_prev(dllist_t *l, int32_t key) { if (l == (dllist_t *) NULL) return ERR_NO_LIST; if (l->head == (node_t *) NULL) return ERR_EMPTY_LIST; node_t *p = l->head->next; node_t *r = (node_t *) NULL; while (p != (node_t *) NULL) { if (p->id == key) { r = p->prev; if (r == l->head) { l->head = p; p->prev = (node_t *) NULL; } else { p->prev = r->prev; r->prev->next = p; } free(r); l->len--; r = (node_t *) NULL; break; } p = p->next; } return SUCCESS; }
code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.h
#ifndef _D_L_LIST_H_ #define _D_L_LIST_H_ #include <stdint.h> #define SUCCESS 0 #define ERR_NO_LIST -1 #define ERR_EMPTY_LIST -2 #define ERR_MALLOC_FAIL -3 typedef struct node_s { int32_t id; int32_t data; struct node_s *next; struct node_s *prev; } node_t ; typedef struct dllist_s { int32_t len; int32_t tail_id; node_t *head; node_t *tail; } dllist_t; dllist_t * dl_create (); int8_t dl_destroy (dllist_t **l); int8_t dl_insert_beginning (dllist_t *l, int32_t value); int8_t dl_insert_end (dllist_t *l, int32_t value); int8_t dl_insert_after (dllist_t *l, int32_t key, int32_t value); int8_t dl_insert_before (dllist_t *l, int32_t key, int32_t value); int8_t dl_remove_beginning (dllist_t *l); int8_t dl_remove_end (dllist_t *l); int8_t dl_remove_next (dllist_t *l, int32_t key); int8_t dl_remove_prev (dllist_t *l, int32_t key); #endif
code/data_structures/src/list/doubly_linked_list/doubly_linked_list.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* Contributed by Vaibhav Jain (vaibhav29498) */ #include <iostream> #include <cstdlib> using namespace std; template <typename T> struct node { T info; node* pre; // Holds the pointer to the previous node node* next; // Holds the pointer to the next node node(); }; template <typename T> node<T>::node() { info = 0; pre = nullptr; next = nullptr; } template <class T> class doubleLinkedList { node<T>* head; public: doubleLinkedList(); int listSize(); void insertNode(T, int); void deleteNode(int); void print(); void reversePrint(); void insertionSort(); }; template <class T> doubleLinkedList<T>::doubleLinkedList() { head = nullptr; } template <class T> int doubleLinkedList<T>::listSize() { int i = 0; node<T> *ptr = head; // The loop below traverses the list to find out the size while (ptr != nullptr) { ++i; ptr = ptr->next; } return i; } template <class T> void doubleLinkedList<T>::insertNode(T i, int p) { node<T> *ptr = new node<T>, *cur = head; ptr->info = i; if (cur == nullptr) head = ptr; // New node becomes head if the list is empty else if (p == 1) { // Put the node at the beginning of the list and change head accordingly ptr->next = head; head->pre = ptr; head = ptr; } else if (p > listSize()) { // Navigate to the end of list and add the node to the end of the list while (cur->next != nullptr) cur = cur->next; cur->next = ptr; ptr->pre = cur; } else { // Navigate to 'p'th element of the list and insert the new node before it int n = p - 1; while (n--) cur = cur->next; ptr->pre = cur->pre; ptr->next = cur; cur->pre->next = ptr; cur->pre = ptr; } cout << "Node inserted!" << endl; } template <class T> void doubleLinkedList<T>::deleteNode(int p) { if (p > listSize()) { // List does not have a 'p'th node cout << "Underflow!" << endl; return; } node<T> *ptr = head; if (p == 1) { // Update head when the first node is being deleted head = head->next; head->pre = nullptr; delete ptr; } else if (p == listSize()) { // Navigate to the end of the list and delete the last node while (ptr->next != nullptr) ptr = ptr->next; ptr->pre->next = nullptr; delete ptr; } else { // Navigate to 'p'th element of the list and delete that node int n = p - 1; while (n--) ptr = ptr->next; ptr->pre->next = ptr->next; ptr->next->pre = ptr->pre; delete ptr; } cout << "Node deleted!" << endl; } template <class T> void doubleLinkedList<T>::print() { // Traverse the entire list and print each node node<T> *ptr = head; while (ptr != nullptr) { cout << ptr->info << " -> "; ptr = ptr->next; } cout << "NULL" << endl; } template <class T> void doubleLinkedList<T>::reversePrint() { node<T> *ptr = head; // First, traverse to the last node of the list while (ptr->next != nullptr) ptr = ptr->next; // From the last node, use `pre` attribute to traverse backwards and print each node in reverse order while (ptr != nullptr) { cout << ptr->info << " <- "; ptr = ptr->pre; } cout << "NULL" << endl; } template <class T> void doubleLinkedList<T>::insertionSort() { if (!head || !head->next) { // The list is empty or has only one element, which is already sorted. return; } node<T> *sorted = nullptr; // Initialize a sorted sublist node<T> *current = head; while (current) { node<T> *nextNode = current->next; if (!sorted || current->info < sorted->info) { // If the sorted list is empty or current node's value is smaller than the // sorted list's head,insert current node at the beginning of the sorted list. current->next = sorted; current->pre = nullptr; if (sorted) { sorted->pre = current; } sorted = current; } else { // Traverse the sorted list to find the appropriate position for the current node. node<T> *temp = sorted; while (temp->next && current->info >= temp->next->info) { temp = temp->next; } // Insert current node after temp. current->next = temp->next; current->pre = temp; if (temp->next) { temp->next->pre = current; } temp->next = current; } current = nextNode; // Move to the next unsorted node } // Update the head of the list to point to the sorted sublist. head = sorted; cout<<"Sorting Complete"<<endl; } int main() { doubleLinkedList<int> l; int m, i, p; while (true) { system("cls"); cout << "1.Insert" << endl << "2.Delete" << endl << "3.Print" << endl << "4.Reverse Print" << endl << "5.Sort" << endl << "6.Exit" << endl; cin >> m; switch (m) { case 1: cout << "Enter info and position "; cin >> i >> p; l.insertNode(i, p); break; case 2: cout << "Enter position "; cin >> p; l.deleteNode(p); break; case 3: l.print(); break; case 4: l.reversePrint(); break; case 5: l.insertionSort(); break; case 6: exit(0); default: cout << "Invalid choice!" << endl; } system("pause"); } return 0; }
code/data_structures/src/list/doubly_linked_list/doubly_linked_list.go
// Part of Cosmos by OpenGenus Foundation package main import ( "fmt" ) type Node struct { key interface{} next *Node prev *Node } type DoubleLinkedList struct { head *Node tail *Node } func (l *DoubleLinkedList) Insert(key interface{}) { newNode := &Node{key, l.head, nil} if l.head != nil { l.head.prev = newNode } l.head = newNode } func (l *DoubleLinkedList) Delete(key interface{}) { temp := l.head prev := &Node{} if temp != nil && temp.key == key { l.head = temp.next temp.next.prev = l.head return } for temp != nil && temp.key != key { prev = temp temp = temp.next } if temp == nil { return } prev.next = temp.next } func (l *DoubleLinkedList) Show() { list := l.head for list != nil { fmt.Printf("%+v <-> ", list.key) list = list.next } fmt.Println() } func main() { l := DoubleLinkedList{} l.Insert(1) l.Insert(2) l.Insert(3) l.Insert(4) l.Insert(5) l.Insert(6) l.Delete(1) l.Delete(9) l.Show() }
code/data_structures/src/list/doubly_linked_list/doubly_linked_list.java
import java.util.*; /* An implementation of Doubly Linked List of integer type */ /* Methods : 1. Insert a particular value at a particular position 2. Delete node at a particular position 3. Traverse the list in forward direction 4. Traverse the list in reverse direction */ class Node { public Node next; public Node prev; int data; public Node(int data){ this.data = data; } } class DoublyLinkedList { private Node first; private Node last; private int n = 0; //size /*-----Insert Method-----*/ public void insert(int pos, int data){ if (pos > n + 1){ pos = n + 1; } Node newNode = new Node(data); if (first == null) { first = newNode; last = first; n++; return; } if (pos == 1){ newNode.next = first; first.prev = newNode; first = newNode; n++; return; } if (pos == n + 1){ newNode.prev = last; last.next = newNode; last = newNode; n++; return; } int c = 1; Node cur = first; while (c != pos){ c++; cur = cur.next; } newNode.next = cur; newNode.prev = cur.prev; cur.prev.next = newNode; cur.prev = newNode; n++; } /*-----Delete Method-----*/ public void delete(int pos){ if (n == 0) { System.out.println("List is Empty!"); return; } if(pos > n) { pos = n; } if (pos == 1) { first = first.next; first.prev = null; return; } int c = 1; Node cur = first; while (c != pos) { c++; cur = cur.next; } if (cur.prev != null) { cur.prev.next = cur.next; } if (cur.next != null) { cur.next.prev = cur.prev; } n--; } /*-----Print in forward direction-----*/ public void display() { Node cur = first; while (cur != null) { System.out.print(cur.data + "->"); cur = cur.next; } System.out.println("null"); } /*-----Print in reverse direction-----*/ public void reverseDisplay() { Node cur = last; while (cur != null) { System.out.print(cur.data + "->"); cur = cur.prev; } System.out.println("null"); } } class App { public static void main(String[] args) { Scanner sc = new Scanner(System.in); DoublyLinkedList l = new DoublyLinkedList(); while (true) { System.out.println("1.Insert"); System.out.println("2.Delete"); System.out.println("3.Print"); System.out.println("4.Print in reverse order"); System.out.println("5.Exit"); int c = sc.nextInt(); switch(c) { case 1: System.out.println("Enter insertion position"); int pos = sc.nextInt(); System.out.println("Enter value"); int val = sc.nextInt(); l.insert(pos, val); break; case 2: System.out.println("Enter deletion position"); pos = sc.nextInt(); l.delete(pos); break; case 3: l.display(); break; case 4: l.reverseDisplay(); break; case 5: return; default: return; } } } }
code/data_structures/src/list/doubly_linked_list/doubly_linked_list.js
/** Source: https://github.com/brunocalou/graph-theory-js/blob/master/src/data_structures/linked_list.js */ /**@module dataStructures */ "use strict"; /** * Node class * @constructor * @public * @param {any} value - The value to be stored */ function Node(value) { this.value = value; this.next = null; this.prev = null; } /** * Linked list class * @constructor */ function LinkedList() { /**@private * @type {node} */ this._front = null; /**@private * @type {node} */ this._back = null; /**@private * @type{number} */ this._length = 0; Object.defineProperty(this, "length", { get: function() { return this._length; } }); } /** * Inserts the element at the specified position in the list. If the index is not specified, will append * it to the end of the list * @param {any} element - The element to be added * @param {number} index - The index where the element must be inserted */ LinkedList.prototype.add = function(element, index) { if (index > this._length || index < 0) { throw new Error("Index out of bounds"); } else { if (index === undefined) { //Add the element to the end index = this._length; } var node = new Node(element); if (index === 0) { //Add the element to the front if (this._length !== 0) { node.next = this._front; this._front.prev = node; } else { //Add the element to the back if the list is empty this._back = node; } this._front = node; } else if (index === this._length) { //Add the element to the back if (this._length !== 0) { node.prev = this._back; this._back.next = node; } this._back = node; } else { //Add the element on the specified index var current_node = this._front; var i; //Check if the index is closer to the front or to the back and performs the //insertion accordingly if (index < this._length / 2) { for (i = 0; i < this._length; i += 1) { if (i === index) { break; } //Get the next node current_node = current_node.next; } } else { current_node = this._back; for (i = this._length - 1; i > 0; i -= 1) { if (i === index) { break; } //Get the previous node current_node = current_node.prev; } } node.prev = current_node.prev; node.next = current_node; current_node.prev.next = node; current_node.prev = node; } this._length += 1; } }; /** * Inserts the element at the begining of the list * @param {any} element - The element to be added */ LinkedList.prototype.addFirst = function(element) { this.add(element, 0); }; /** * Inserts the element at the end of the list * @param {any} element - The element to be added */ LinkedList.prototype.addLast = function(element) { this.add(element); }; /** * Removes all the elements of the list */ LinkedList.prototype.clear = function() { while (this._length) { this.pop(); } }; /** * Returns if the list contains the element * @param {any} element - The element to be checked * @returns {boolean} True if the list contains the element */ LinkedList.prototype.contains = function(element) { var found_element = false; this.every(function(elem, index) { if (elem === element) { found_element = true; return false; } return true; }); return found_element; }; /** * The function called by the forEach method. * @callback LinkedList~iterateCallback * @function * @param {any} element - The current element * @param {number} [index] - The index of the current element * @param {LinkedList} [list] - The linked list it is using */ /** * Performs the fn function for all the elements of the list, untill the callback function returns false * @param {iterateCallback} fn - The function the be executed on each element * @param {object} [this_arg] - The object to use as this when calling the fn function */ LinkedList.prototype.every = function(fn, this_arg) { var current_node = this._front; var index = 0; while (current_node) { if (!fn.call(this_arg, current_node.value, index, this)) { break; } current_node = current_node.next; index += 1; } }; /** * Performs the fn function for all the elements of the list * @param {iterateCallback} fn - The function the be executed on each element * @param {object} [this_arg] - The object to use as this when calling the fn function */ LinkedList.prototype.forEach = function(fn, this_arg) { var current_node = this._front; var index = 0; while (current_node) { fn.call(this_arg, current_node.value, index, this); current_node = current_node.next; index += 1; } }; /** * Returns the element at the index, if any * @param {number} index - The index of the element to be returned * @returns {any} The element at the specified index, if any. Returns undefined otherwise */ LinkedList.prototype.get = function(index) { if (index < 0 || index >= this._length) { return undefined; } var node = this._front; for (var i = 0; i < this._length; i += 1) { if (i === index) { return node.value; } node = node.next; } }; /** * Returns the first element in the list * @returns {any} The first element in the list */ LinkedList.prototype.getFirst = function() { return this.get(0); }; /** * Returns the last element in the list * @returns {any} The last element in the list */ LinkedList.prototype.getLast = function() { if (this._back != null) { return this._back.value; } }; /** * Returns the index of the element in the list * @param {any} element - The element to search * @returns {number} The index of the element in the list, or -1 if not found */ LinkedList.prototype.indexOf = function(element) { var node = this._front; for (var i = 0; i < this._length; i += 1) { if (node.value === element) { return i; } node = node.next; } return -1; }; /** * Returns if the list is empty * @returns {boolean} If the list if empty */ LinkedList.prototype.isEmpty = function() { return this._length === 0; }; /** * Returns the last index of the element in the list * @param {any} element - The element to search * @returns {number} The last index of the element in the list, -1 if not found */ LinkedList.prototype.lastIndexOf = function(element) { var current_node = this._back; var index = this._length - 1; while (current_node) { if (current_node.value === element) { break; } current_node = current_node.prev; index -= 1; } return index; }; /** * Retrieves the first element without removing it. * This method is equivalent to getFirst * @see getFirst * @returns {any} The first element */ LinkedList.prototype.peek = function() { return this.get(0); }; /** * Removes and returns the first element of the list. * This method is equivalent to removeFirst * @see removeFirst * @returns {any} The removed element */ LinkedList.prototype.pop = function() { return this.removeFirst(); }; /** * Inserts the element to the end of the list * This method is equivalent to addFirst * @see addFirst */ LinkedList.prototype.push = function(element) { this.addFirst(element); }; /** * Removes and retrieves the element at the specified index. * If not specified, it will remove the first element of the list * @param {number} index - The index of the element to be removed * @returns {any} The removed element */ LinkedList.prototype.remove = function(index) { if (index > this._length - 1 || index < 0 || this._length === 0) { throw new Error("Index out of bounds"); } else { var removed_node; if (index === 0) { //Remove the first element removed_node = this._front; this.removeNode(this._front); } else if (index === this._length - 1) { //Remove the last element removed_node = this._back; this.removeNode(this._back); } else { //Remove the element at the specified index var node = this._front; var i; if (index < this._length / 2) { for (i = 0; i < this._length; i += 1) { if (i === index) { removed_node = node; this.removeNode(removed_node); break; } node = node.next; } } else { node = this._back; for (i = this._length - 1; i > 0; i -= 1) { if (i === index) { removed_node = node; this.removeNode(removed_node); break; } node = node.prev; } } } this._length -= 1; return removed_node.value; } }; /** * Removes and retrieves the first element of the list * @returns {any} The removed element */ LinkedList.prototype.removeFirst = function() { if (this._length > 0) { return this.remove(0); } }; /** * Removes and retrieves the first occurrence of the element in the list * @returns {any} The removed element */ LinkedList.prototype.removeFirstOccurrence = function(element) { var node = this._front; var index = 0; while (node) { if (node.value === element) { this.removeNode(node); return node.value; } node = node.next; index += 1; } }; /** * Removes and retrieves the last element of the list * @returns {any} The removed element */ LinkedList.prototype.removeLast = function() { if (this._length > 0) { return this.remove(this._length - 1); } }; /** * Removes and retrieves the last occurrence of the element in the list * @returns {any} The removed element */ LinkedList.prototype.removeLastOccurrence = function(element) { var node = this._back; var index = this._length - 1; while (node) { if (node.value === element) { this.removeNode(node); return node.value; } node = node.prev; index -= 1; } }; /** * Removes the node from the list * @returns {any} The removed node */ LinkedList.prototype.removeNode = function(node) { if (node === this._front) { if (this._length > 1) { this._front.next.prev = null; this._front = this._front.next; } else { this._front = null; this._back = null; } node.next = null; } else if (node === this._back) { this._back.prev.next = null; this._back = this._back.prev; node.prev = null; } else { var prev_node = node.prev; var next_node = node.next; prev_node.next = next_node; next_node.prev = prev_node; node.next = null; node.prev = null; } }; /** * Replaces the element at the specified position in the list. * @param {any} element - The new element * @param {number} index - The index where the element must be replaced * @returns {any} The element previously at the specified position */ LinkedList.prototype.set = function(element, index) { if (index > this._length - 1 || index < 0 || this._length === 0) { throw new Error("Index out of bounds"); } else { var node = this._front; var old_element; for (var i = 0; i < this._length; i += 1) { if (i === index) { old_element = node.value; node.value = element; return old_element; } node = node.next; } } }; /** * Returns the size of the list * @returns {number} The size of the list */ LinkedList.prototype.size = function() { return this._length; }; /** * Converts the list to an array * @returns {array} The converted list in an array format */ LinkedList.prototype.toArray = function() { var array = new Array(this._length); this.forEach(function(element, index) { array[index] = element; }); return array; }; module.exports = LinkedList;
code/data_structures/src/list/doubly_linked_list/doubly_linked_list.py
# Part of Cosmos by OpenGenus Foundation class DoublyLinkedList: class Node: def __init__(self, data, prevNode, nextNode): self.data = data self.prevNode = prevNode self.nextNode = nextNode def __init__(self, data=None): self.first = None self.last = None self.count = 0 def addFirst(self, data): if self.count == 0: self.first = self.Node(data, None, None) self.last = self.first elif self.count > 0: # create a new node pointing to self.first node = self.Node(data, None, self.first) # have self.first point back to the new node self.first.prevNode = node # finally point to the new node as the self.first self.first = node self.current = self.first self.count += 1 def popFirst(self): if self.count == 0: raise RuntimeError("Cannot pop from an empty linked list") result = self.first.data if self.count == 1: self.first = None self.last = None else: self.first = self.first.nextNode self.first.prevNode = None self.current = self.first self.count -= 1 return result def popLast(self): if self.count == 0: raise RuntimeError("Cannot pop from an empty linked list") result = self.last.data if self.count == 1: self.first = None self.last = None else: self.last = self.last.prevNode self.last.nextNode = None self.count -= 1 return result def addLast(self, data): if self.count == 0: self.addFirst(0) else: self.last.nextNode = self.Node(data, self.last, None) self.last = self.last.nextNode self.count += 1 def __repr__(self): result = "" if self.count == 0: return "..." cursor = self.first for i in range(self.count): result += "{}".format(cursor.data) cursor = cursor.nextNode if cursor is not None: result += " --- " return result def __iter__(self): # lets Python know this class is iterable return self def __next__(self): # provides things iterating over class with next element if self.current is None: # allows us to re-iterate self.current = self.first raise StopIteration else: result = self.current.data self.current = self.current.nextNode return result def __len__(self): return self.count dll = DoublyLinkedList() dll.addFirst("days") dll.addFirst("dog") dll.addLast("of summer") assert list(dll) == ["dog", "days", "of summer"] assert dll.popFirst() == "dog" assert list(dll) == ["days", "of summer"] assert dll.popLast() == "of summer" assert list(dll) == ["days"]
code/data_structures/src/list/doubly_linked_list/doubly_linked_list.swift
public class DoublyLinkedList<T> { public class Node<T> { var value: T var next: Node? weak var previous: Node? // weak is used to avoid ownership cycles public init(value: T) { self.value = value } } fileprivate var head: Node<T>? private var tail: Node<T>? public var isEmpty: Bool { return head == nil } public var first: Node<T>? { return head } public var last: Node<T>? { return tail } public func append(value: T) { let newNode = Node(value: value) if let tailNode = tail { newNode.previous = tailNode tailNode.next = newNode } else { head = newNode } tail = newNode } public func nodeAt(_ index: Int) -> Node<T>? { if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } // e.g. list[0] public subscript(index: Int) -> T { let node = nodeAt(index) assert(node != nil) return node!.value } public func insert(value: T, atIndex index: Int) { let (prev, next) = nodesBeforeAndAfter(index: index) // 1 let newNode = Node(value: value) // 2 newNode.previous = prev newNode.next = next prev?.next = newNode next?.previous = newNode if prev == nil { // 3 head = newNode } } public var count: Int { if var node = head { var c = 1 while let next = node.next { node = next c += 1 } return c } else { return 0 } } public func remove(node: Node<T>) -> String { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev if next == nil { tail = prev } node.previous = nil node.next = nil return node.value as! String } public func removeAll() { head = nil tail = nil } // Helper functions private func nodesBeforeAndAfter(index: Int) -> (Node<T>?, Node<T>?) { assert(index >= 0) var i = index var next = head var prev: Node<T>? while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0) return (prev, next) } } extension DoublyLinkedList { public func reverse() { var node = head tail = node while let currentNode = node { node = currentNode.next swap(&currentNode.next, &currentNode.previous) head = currentNode } } } extension DoublyLinkedList { public func map<U>(transform: (T) -> U) -> DoublyLinkedList<U> { let result = DoublyLinkedList<U>() var node = head while node != nil { result.append(value: transform(node!.value)) node = node!.next } return result } public func filter(predicate: (T) -> Bool) -> DoublyLinkedList<T> { let result = DoublyLinkedList<T>() var node = head while node != nil { if predicate(node!.value) { result.append(value: node!.value) } node = node!.next } return result } } extension DoublyLinkedList: CustomStringConvertible { public var description: String { var text = "[" var node = head while node != nil { text += "\(node!.value)" node = node!.next if node != nil { text += ", " } } return text + "]" } } extension DoublyLinkedList { convenience init(array: Array<T>) { self.init() for element in array { self.append(element) } } }
code/data_structures/src/list/doubly_linked_list/menu_interface/dlink.h
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #define MAX_LENGTH 20 void insert_beg(int num); void insert_end(int num); void insert_at_loc(int num, int loc); void insert_after_value(int num, int val); void delete_beg(); void delete_end(); void delete_node(int loc); void delete_value(int num); void replace_value(int num, int val); void replace_node(int num, int loc); void sortlist(); void delete_dup_vals(); int length(); void display(); void clear(void); typedef struct dlist { int info; struct dlist* next; struct dlist* prev; }dlist; dlist *start = NULL, *curr = NULL, *node = NULL, *pre = NULL; void insert_beg(int num) { node = (dlist*) malloc(sizeof(dlist*)); node->info = num; node->prev = NULL; if (start == NULL) { node->next = NULL; start = node; } else { node->next = start; start->prev = node; start = node; } } void insert_end(int num) { node = (dlist*) malloc(sizeof(dlist*)); node->info = num; node->next = NULL; if (start == NULL) { node->prev = NULL; start = node; } else { curr = start; while (curr->next != NULL) curr = curr->next; curr->next = node; node->prev = curr; } } void insert_at_loc(int num, int loc) { int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!!\n"); return; } node = (dlist*) malloc(sizeof(dlist*)); node->info = num; if (start == NULL) { node->next = NULL; node->prev = NULL; start = node; } else { curr = start; int i = 1; while (curr != NULL && i < loc) { pre = curr; curr = curr->next; i++; } if (pre != NULL) pre->next = node; node->next = curr; node->prev = pre; if(curr != NULL) curr->prev = node; } } void insert_after_value(int num, int val) { node = (dlist*) malloc(sizeof(dlist*)); node->info = num; if (start == NULL) { node->next = NULL; node->prev = NULL; start = node; } else { curr = start; while (curr != NULL && curr->info != val) curr = curr->next; if (curr == NULL) { printf("Value not found!! Please enter again\n"); return; } node->next = curr->next; curr->next->prev = node; curr->next = node; node->prev = curr; } } void delete_beg() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; start = start->next; start->prev = NULL; free(curr); } void delete_end() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr->next != NULL) { pre = curr; curr = curr->next; } pre->next = NULL; free(curr); } void delete_node(int loc) { if (start == NULL) { printf("List is empty\n"); return; } int n = length(); if (loc > n || loc < 0) { printf("Location is invalid\n"); return; } curr = start; int i = 1; while (curr != NULL && i<loc) { pre = curr; curr = curr->next; i++; } pre->next = curr->next; curr->next->prev = pre; free(curr); } void delete_value(int num) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; if (start->info == num) { start = start->next; start->prev = NULL; free(curr); } curr = start; while (curr != NULL && curr->info != num) { pre = curr; curr = curr->next; } if (curr == NULL) { printf("Value not found! Please try again\n"); return; } pre->next = curr->next; curr->next->prev = pre; free(curr); } void replace_value(int num,int val) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr != NULL && curr->info != num) curr = curr->next; if (curr == NULL) { printf("Value not found! Please try again\n"); return; } curr->info = val; } void replace_node(int loc, int num) { if (start == NULL) { printf("List is empty\n"); return; } int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!! Try again\n"); return; } curr = start; int i = 1; while (curr != NULL && i<loc) { curr = curr->next; i++; } curr->info = num; } void sortlist() { if (start == NULL) { printf("List is empty\n"); return; } for (curr=start; curr!= NULL; curr=curr->next) { for(pre=curr->next; pre!=NULL; pre=pre->next) { if ((curr->info > pre->info)) { int temp = curr->info; curr->info = pre->info; pre->info = temp; } } } } void delete_dup_vals() { if (start == NULL) { printf("List is empty\n"); return; } sortlist(); curr = start; while (curr->next != NULL) { if(curr->info == curr->next->info) { pre = curr->next->next; free(curr->next); curr->next = pre; pre->prev = curr; } else curr = curr->next; } } int length() { if (start == NULL) return 0; int i = 1; curr = start; while (curr != NULL) { curr = curr->next; i++; } return i; } void display() { if (start == NULL) { printf("The list is empty\n"); return; } curr = start; while (curr != NULL) { printf("%d\n", curr->info); curr = curr->next; } } void display_reverse() { if (start == NULL) { printf("The list is empty\n"); return; } curr = start; while (curr->next != NULL) curr = curr->next; while (curr != NULL) { printf("%d\n", curr->info); curr = curr->prev; } } void writefile(char *filename) { char path[MAX_LENGTH] = "./files/"; strcat(path,filename); FILE *fp; fp = fopen(path,"w"); curr = start; while (curr != NULL) { fprintf(fp,"%d\n", curr->info); curr = curr->next; } fclose(fp); } void readfile(char *filename) { start = NULL; char path[MAX_LENGTH] = "./files/"; strcat(path,filename); FILE *fp; int num; fp = fopen(path, "r"); while(!feof(fp)) { fscanf(fp, "%i\n", &num); insert_end(num); } fclose(fp); } void listfile() { DIR *d = opendir("./files/"); struct dirent *dir; if (d) { printf("Current list of files\n"); while ((dir = readdir(d)) != NULL) { if (strcmp(dir->d_name, "..") == 0 || strcmp(dir->d_name,".") == 0) continue; printf("%s\n", dir->d_name); } closedir(d); } }
code/data_structures/src/list/doubly_linked_list/menu_interface/doubly_link.c
/* This project aims to demonstrate various operations on linked lists. It uses a clean command line interface and provides a baseline to make linked list applications in C. There are two files. The C file containing main() function and invoking functions. The dlink.h header file where all functions are implemented. */ #include "dlink.h" /* For clearing screen in Windows and UNIX-based OS */ #ifdef _WIN32 #define CLEAR "cls" #else /* In any other OS */ #define CLEAR "clear" #endif /* For cross-platform delay function for better UI transition */ #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> /* for sleep() function */ #endif void msleep(int ms) { #ifdef _WIN32 Sleep(ms); #else usleep(ms * 1000); #endif } int menu(); void print(); int main() { int n; printf("WELCOME TO THE LINKED LIST APPLICATION\n"); clear(); usleep(500000); do { clear(); msleep(500); print(); n = menu(); }while(n!=17); clear(); } void print() { printf("1. Insert at beginning\n"); printf("2. Insert at end\n"); printf("3. Insert at a particular location\n"); printf("4. Insert after a particular value\n"); printf("5. Delete a number from beginning of list\n"); printf("6. Delete a number from end of list\n"); printf("7. Delete a particular node in the list\n"); printf("8. Delete a particular value in the list\n"); printf("9. Replace a particular value with another in a list\n"); printf("10. Replace a particular node in the list\n"); printf("11. Sort the list in ascending order\n"); printf("12. Delete all duplicate values and sort\n"); printf("13. Display\n"); printf("14. Display in reverse\n"); printf("15. Write to File\n"); printf("16. Read from a File\n"); printf("17. Quit\n"); } int menu() { int n, a, b; char *filename = (char *) malloc(MAX_LENGTH*sizeof(char)); printf("Select the operation you want to perform (17 to Quit): "); scanf("%d", &n); switch(n) { case 1: printf("Enter the number you want to insert: "); scanf("%d", &a); insert_beg(a); break; case 2: printf("Enter the number you want to insert: "); scanf("%d", &a); insert_end(a); break; case 3: printf("Enter the number you want to insert: "); scanf("%d", &a); printf("Enter the location in which to insert: "); scanf("%d", &b); insert_at_loc(a, b); break; case 4: printf("Enter the number you want to insert: "); scanf("%d", &a); printf("Enter the value after which to insert: "); scanf("%d", &b); insert_after_value(a, b); break; case 5: delete_beg(); break; case 6: delete_end(); break; case 7: printf("Enter the location of node to delete: "); scanf("%d", &a); delete_node(a); break; case 8: printf("Enter the value you want to delete: "); scanf("%d", &a); delete_value(a); break; case 9: printf("Enter the value you want to replace: "); scanf("%d", &a); printf("Enter the new value: "); scanf("%d",&b); replace_value(a, b); break; case 10: printf("Enter the node location you want to replace: "); scanf("%d", &a); printf("Enter the new number: "); scanf("%d", &b); replace_node(a, b); break; case 11: sortlist(); break; case 12: delete_dup_vals(); break; case 13: display(); usleep(5000); break; case 14: display_reverse(); usleep(5000); break; case 15: printf("Enter the name of file to write to: "); scanf("%s", filename); writefile(filename); break; case 16: listfile(); printf("Enter the name of file to read from: "); scanf("%s", filename); readfile(filename); break; case 17: return n; break; } } void clear(void) { system(CLEAR); }
code/data_structures/src/list/merge_two_sorted_lists/Merging_two_sorted.cpp
//Write a SortedMerge function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order #include <bits/stdc++.h> #define mod 1000000007 #define lli long long int using namespace std; class node{ public: int data; node* next; node(int x){ data=x; next=NULL; } }; void insertATHead(node* &head,int val){ node* n=new node(val); n->next=head; head=n; } void InsertAtTail(node* &head,int val){ node* n=new node(val); node* temp=head; if(temp==NULL){ head=n; return; } while(temp->next!=NULL){ temp=temp->next; } temp->next=n; } void display(node* head){ node* temp=head; while(temp!=NULL){ cout<<temp->data<<" "; temp=temp->next; } cout<<endl; } node* mergerecur(node* &head1,node* &head2){ node* result; if(head1==NULL){ return head2; } if(head2==NULL){ return head1; } if(head1->data<head2->data){ result=head1; result->next=mergerecur(head1->next,head2); } else{ result=head2; result->next=mergerecur(head1,head2->next); } return result; } node* merge(node* &head1,node*&head2){ node* p1=head1; node* p2=head2; node* dummynode=new node(-1); node* p3=dummynode; while(p1!=NULL && p2!=NULL){ if(p1->data<p2->data){ p3->next=p1; p1=p1->next; } else{ p3->next=p2; p2=p2->next; } p3=p3->next; } while(p1!=NULL){ p3->next=p1; p1=p1->next; p3=p3->next; } while(p2!=NULL){ p3->next=p2; p2=p2->next; p3=p3->next; } return dummynode; } int main(){ node* head1=NULL; node* head2=NULL; InsertAtTail(head1,1); InsertAtTail(head1,4); InsertAtTail(head1,5); InsertAtTail(head1,7); InsertAtTail(head2,3); InsertAtTail(head2,4); InsertAtTail(head2,6); display(head1); display(head2); node* newhead=mergerecur(head1,head2); display(newhead); return 0; }
code/data_structures/src/list/singly_linked_list/menu_interface/link.h
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #define MAX_LENGTH 20 typedef struct list { int info; struct list* next; }list; list *start=NULL, *node=NULL, *curr=NULL, *prev=NULL; void insert_beg(int); void insert_end(int); void insert_at_loc(int, int); void insert_after_value(int, int); void delete_beg(); void delete_end(); void delete_node(int); void delete_value(int); void replace_node(int, int); void replace_value(int, int); void delete_dup_vals(); int length(); void display(); void reverse(); void clear(void); void sortlist(); void writefile(char *filename); void readfile(); void insert_beg(int num) { node = (list*)malloc(sizeof(list*)); node->info = num; if (start == NULL) { node->next = NULL; start = node; } else { node->next = start; start = node; } } void insert_end(int num) { node = (list*)malloc(sizeof(list*)); node->info = num; node->next = NULL; if (start == NULL) start = node; else { curr = start; while (curr->next != NULL) curr=curr->next; curr->next=node; } } void insert_at_loc(int num, int loc) { int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!! Try again\n"); return; } node = (list*)malloc(sizeof(list*)); node->info = num; node->next = NULL; if (start == NULL) start = node; else { curr = start; int i = 1; while (curr != NULL && i<loc) { prev = curr; curr = curr->next; i++; } node->next = curr; prev->next = node; } } void insert_after_value(int num, int val) { node = (list*)malloc(sizeof(list*)); node->info = num; if (start == NULL) start = node; else { curr = start; while(curr != NULL && curr->info != val) curr=curr->next; if (curr == NULL) { printf("Value was not found!! Try again\n"); return; } node->next = curr->next; curr->next = node; } } void delete_beg() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; start = start->next; free(curr); } void delete_end() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr->next != NULL) { prev = curr; curr = curr->next; } prev->next = NULL; free(curr); } void delete_node(int num) { int n = length(); if (num > n || num < 0) { printf("Location is invalid!! Try again\n"); return; } if (start == NULL) { printf("List is empty\n"); return; } curr = start; int i = 1; while (curr != NULL && i < num) { prev = curr; curr = curr->next; i++; } prev->next = curr->next; free(curr); } void delete_value(int num) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; if (start->info == num) { start = start->next; free(curr); } curr = start; while (curr != NULL && curr->info != num) { prev = curr; curr = curr->next; } if (curr == NULL) { printf("Value not found! Try again\n"); return; } prev->next = curr->next; free(curr); } void replace_node(int num, int loc) { int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!! Try again\n"); return; } if (start == NULL) { printf("List is empty\n"); return; } curr = start; int i = 1; while (curr != NULL && i < loc) { curr = curr->next; i++; } curr->info = num; } void replace_value(int num, int val) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr != NULL && curr->info != val) curr = curr->next; if (curr == NULL) { printf("Value not found! Try again\n"); return; } curr->info = num; } void delete_dup_vals() { if (start == NULL) { printf("List is empty\n"); return; } sortlist(); curr = start; while (curr->next != NULL) { if (curr->info == curr->next->info) { prev = curr->next->next; free(curr->next); curr->next = prev; } else curr = curr->next; } } int length() { if (start == NULL) return (0); int i = 1; curr = start; while (curr != NULL) { curr = curr->next; i++; } return (i); } void display() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr!=NULL) { printf("%d\n", curr->info); curr = curr->next; } } void reverse() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; prev = curr->next; curr->next = NULL; while (prev->next != NULL) { node = prev->next; prev->next = curr; curr = prev; prev = node; } prev->next = curr; start = prev; } void sortlist() { if (start == NULL) { printf("List is empty\n"); return; } for (curr=start; curr!= NULL; curr=curr->next) { for (prev=curr->next; prev!=NULL; prev=prev->next) { if ((curr->info > prev->info)) { int temp = curr->info; curr->info = prev->info; prev->info = temp; } } } } void writefile(char *filename) { char path[MAX_LENGTH] = "./files/"; strcat(path, filename); FILE *fp; fp = fopen(path, "w"); curr = start; while (curr != NULL) { fprintf(fp,"%d\n", curr->info); curr = curr->next; } fclose(fp); } void readfile(char *filename) { start = NULL; char path[MAX_LENGTH] = "./files/"; strcat(path, filename); FILE *fp; int num; fp = fopen(path, "r"); while (!feof(fp)) { fscanf(fp, "%i\n", &num); insert_end(num); } fclose(fp); } void listfile() { DIR *d = opendir("./files/"); struct dirent *dir; if (d) { printf("Current list of files\n"); while((dir = readdir(d)) != NULL) { if(strcmp(dir->d_name, "..") == 0 || strcmp(dir->d_name,".") == 0) continue; printf("%s\n", dir->d_name); } closedir(d); } }
code/data_structures/src/list/singly_linked_list/menu_interface/singly_list.c
/* This project aims to demonstrate various operations on linked lists. It uses a clean command line interface and provides a baseline to make linked list applications in C. There are two files. The C file containing main() function and invoking functions. The link.h header file where all functions are implemented. */ #include "link.h" /* custom header file to implement functions */ /* For clearing screen in Windows and UNIX-based OS */ #ifdef _WIN32 #define CLEAR "cls" #else /* In any other OS */ #define CLEAR "clear" #endif /* For cross-platform delay function for better UI transition */ #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> /* for sleep() function */ #endif void msleep(int ms) { #ifdef _WIN32 Sleep(ms); #else usleep(ms * 1000); #endif } void print(); void clear(); int menu(); int main() { int c; do { c = menu(); }while(c!=17); } void print() { printf("1. Insert at beginning\n"); printf("2. Insert at end\n"); printf("3. Insert at a particular location\n"); printf("4. Insert after a particular value\n"); printf("5. Delete from beginning\n"); printf("6. Delete from end\n"); printf("7. Delete a particular node\n"); printf("8. Delete a particular value\n"); printf("9. Replace a value at a particular node\n"); printf("10. Replace a particular value in the list\n"); printf("11. Delete all duplicate values and sort\n"); printf("12. Display\n"); printf("13. Reverse\n"); printf("14. Sort(Ascending)\n"); printf("15. Write to File\n"); printf("16. Read from a file\n"); printf("17. Quit\n"); } int menu() { clear(); msleep(500); /* for delay effect 500ms */ print(); int n, a, b; char *filename = (char *) malloc(MAX_LENGTH*sizeof(char)); /* For writing and reading linked list data from file */ printf("Select the operation you want to perform (17 to Quit): "); scanf("%d", &n); switch(n) { case 1: printf("Enter the number you want to insert: "); scanf("%d", &a); insert_beg(a); break; case 2: printf("Enter the number you want to insert: "); scanf("%d", &a); insert_end(a); break; case 3: printf("Enter the number you want to insert: "); scanf("%d", &a); printf("Enter the location in which you want to insert: "); scanf("%d", &b); insert_at_loc(a, b); break; case 4: printf("Enter the number you want to insert: "); scanf("%d", &a); printf("Enter the value after which to insert: "); scanf("%d", &b); insert_after_value(a, b); break; case 5: delete_beg(); break; case 6: delete_end(); break; case 7: printf("Enter the location of node to delete: "); scanf("%d", &a); delete_node(a); break; case 8: printf("Enter the value you want to delete: "); scanf("%d", &a); delete_value(a); break; case 9: printf("Enter the location of node you want to replace: "); scanf("%d", &b); printf("Enter the new number: "); scanf("%d", &a); replace_node(a, b); break; case 10: printf("Enter the value you want to replace: "); scanf("%d", &a); printf("Enter the new number: "); scanf("%d", &b); replace_value(b, a); break; case 11: delete_dup_vals(); break; case 12: display(); msleep(5000); break; case 13: reverse(); break; case 14: sortlist(); break; case 15: printf("Enter the name of file to write to: "); scanf("%s", filename); writefile(filename); break; case 16: listfile(); printf("Enter the name of file to read from: "); scanf("%s", filename); readfile(filename); break; case 17: return (n); } return (0); } void clear(void) { system(CLEAR); /* Cross-platform clear screen */ }
code/data_structures/src/list/singly_linked_list/operations/delete/delete_node_with_key.java
package linkedlist; class LinkedList { Node head; static class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } public void printList() { Node n = head; while(n!=null){ System.out.print(n.data+" "); n = n.next; } } public void delete(int key) { Node temp = head,prev = null; while(temp!=null && temp.data == key) { head = temp.next; return; } while(temp != null && temp.data != key) { prev = temp; temp = temp.next; } if(head == null)return; prev.next = temp.next; } public void push(int data) { Node new_node = new Node(data); new_node.next = head; head = new_node; } public static void main(String args[]) { LinkedList ll = new LinkedList(); ll.push(1); ll.push(2); ll.printList(); System.out.println(); ll.delete(1); ll.printList(); } }
code/data_structures/src/list/singly_linked_list/operations/delete/delete_node_without_head_linked_list.cpp
#include <bits/stdc++.h> using namespace std; // Initializing a Linked List class Node{ public: int data; Node *next; // Constructor for Linked List for a deafult value Node(int data){ this -> data=data; this -> next=NULL; } }; // Print Linked List Function void printList(Node* &head){ Node* temphead = head; while(temphead != NULL){ cout << temphead -> data << " "; temphead = temphead -> next; } cout<<endl; } // Appending elements in the Linked List void insertattail(Node* &tail, int data){ Node *hue = new Node(data); tail->next=hue; tail=hue; } // Deleting a single Node without head Pointer in Linked List // Time Complexity: O(1) // Auxilliary Space: O(1) void delwohead(Node* del){ del->data=del->next->data; del->next=del->next->next; } // Driver Function int main(){ Node* mainode=new Node(1); Node* head=mainode; Node* tail=mainode; Node* nodetobedeleted=mainode; insertattail(tail,3); insertattail(tail,4); insertattail(tail,7); insertattail(tail,9); // Our Linked List right now => 1 3 4 7 9 cout<<"<= Original Linked List =>"<<endl; printList(head); // Let assume we want to delete the 2nd element from the Linked List for(int i=0;i<2;++i){ nodetobedeleted=head; head=head->next; } // This will delete the second element from the Linked List i.e. 3 delwohead(nodetobedeleted); cout<<endl<<"<= New Linked List after deleting second element =>"<<endl; printList(mainode); return 0; }
code/data_structures/src/list/singly_linked_list/operations/delete/delete_nth_node.c
/* delete the nth node from the link list */ /* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #include <stdlib.h> struct node{ /* defining a structure named node */ int data; /* stores data */ struct node* next; /* stores the address of the next node*/ }; void insert(struct node **head , int data) /* inserts the value at the beginning of the list */ { struct node* temp = (struct node*)malloc(sizeof(struct node*)); temp->data = data; temp->next = *head; *head = temp; } void Delete(struct node **head , int n , int *c) /* delete the node at nth position */ { if ( n <= *c ){ struct node* temp1 = *head; if ( n == 1 ){ *head = temp1->next; free(temp1); /* delete temp1 */ return; } int i; for (i = 0 ; i < n-2 ; i++)temp1 = temp1->next; /* temp1 will point to (n-1)th node */ struct node* temp2 = temp1->next; /* nth node */ temp1->next = temp2->next; /* (n+1)th node */ free(temp2); /* delete temp2 */ } else printf("Position does not exists!\n"); } /* Counts no. of nodes in linked list */ int getCount(struct node **head) { int count = 0; /* Initialize count */ struct node* current = *head; /* Initialize current */ while (current != NULL) { count++; current = current->next; } return count; } void result(struct node **head) /* print all the elements of the list */ { struct node* temp = *head; printf("list:"); while ( temp != NULL ){ printf("%d ",temp->data); temp = temp->next; } printf("\n"); } int main() { struct node* head = NULL; /* empty list */ insert ( &head , 2 ); insert ( &head , 4 ); insert ( &head , 5 ); insert ( &head , 7 ); insert ( &head , 8 ); /* List:2 4 5 7 8 */ result ( &head ); int n , c; c = getCount( &head ); printf ("Enter the position:"); scanf ( "%d" , &n ); Delete ( &head , n , &c ); result ( &head ); return (0); }
code/data_structures/src/list/singly_linked_list/operations/detect_cycle/detect_cycle.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> using namespace std; // Singly-Linked List Defined struct Node { int data; Node* next; Node(int val) { data = val; next = NULL; } }; //Function to add nodes to the linked list Node* TakeInput(int n) { Node* head = NULL; //head of the Linked List Node* tail = NULL; //Tail of the Linked List while (n--) { int value; //data value(int) of the node cin >> value; //creating new node Node* newNode = new Node(value); //if the is no elements/nodes in the linked list so far. if (head == NULL) head = tail = newNode; //newNode is the only node in the LL else // there are some elements/nodes in the linked list { tail->next = newNode; // new Node added at the end of the LL tail = newNode; // last node is tail node } } return head; } Node* DetectCycle(Node* head) { Node* slow = head; Node* fast = head; while (fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return fast; } return NULL; } void RemoveCycle(Node* head, Node* intersect_Node) { Node* slow = head; Node* prev = NULL; while (slow != intersect_Node) { slow = slow->next; prev = intersect_Node; intersect_Node = intersect_Node->next; } prev->next = NULL; //cycle removed } void PrintLL(Node* head) { Node* tempPtr = head; // until it reaches the end while (tempPtr != NULL) { //print the data of the node cout << tempPtr->data << " "; tempPtr = tempPtr->next; } cout << endl; } int main() { int n; //size of the linked list cin >> n; Node* head = TakeInput(n); //creating a cycle in the linked list // For n=5 and values 1 2 3 4 5 head->next->next->next->next->next = head->next->next; // change this according tp your input // 1-->2-->3-->4-->5-->3-->4-->5-->3--> ... and so on // PrintLL(head); Uncomment this to check cycle RemoveCycle(head, DetectCycle(head)); PrintLL(head); return 0; }
code/data_structures/src/list/singly_linked_list/operations/detect_cycle/detect_cycle_hashmap.py
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def append(self, element): new_node = Node(data=element) if self.head is None: self.head = new_node return current_node = self.head while current_node.next is not None: current_node = current_node.next current_node.next = new_node def findLoop(self): hash_map = set() current_node = self.head while current_node is not None: if current_node in hash_map: return True hash_map.add(current_node) current_node = current_node.next return False def __repr__(self): all_nodes = [] current_node = self.head while current_node is not None: all_nodes.append(str(current_node.data)) current_node = current_node.next if len(all_nodes) > 0: return " -> ".join(all_nodes) else: return ""
code/data_structures/src/list/singly_linked_list/operations/find/find.c
/* Check weather element is present in link list (iterative method)*/ /* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #include <stdlib.h> struct node{ /* defining a structure named node */ int data; struct node* next; }; void insert(struct node **head , int data) /* insert an integer to the beginning of the list */ { struct node* temp = (struct node*)malloc(sizeof(struct node*)); temp->data = data; temp->next = *head; *head = temp; } void find(struct node **head , int n) /* delete the node at nth position */ { struct node* temp1 = *head; while (temp1 != NULL) { if (temp1->data == n){ printf ("Element found\n"); return;} temp1 = temp1->next; } printf ("Element Not found \n"); return ; } void result(struct node **head) /* print all the elements of the list */ { struct node* temp = *head; printf ("list:"); while (temp != NULL){ printf ("%d " , temp->data); temp = temp->next; } printf ("\n"); } int main() { struct node* head = NULL; /* empty list */ insert (&head , 2); insert (&head , 4); insert (&head , 5); insert (&head , 7); insert (&head , 8); /* List:2 4 5 7 8 */ result (&head); int n; printf ("Enter the element:"); scanf ("%d" , &n); find (&head , n); return (0); }
code/data_structures/src/list/singly_linked_list/operations/find/find.java
package linkedlist; class LinkedList { Node head; static class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } public void push(int data) { Node new_node = new Node(data); new_node.next = head; head = new_node; } public void printList() { Node n = head; while(n != null) { System.out.print(n.data+" "); n = n.next; } } public boolean search(Node head, int x) { Node current = head; while(current != null) { if(current.data == x) { return true; } current = current.next; } return false; // not found } public static void main(String args[]) { LinkedList ll = new LinkedList(); ll.push(5); ll.push(4); ll.push(3); ll.push(2); if(ll.search(ll.head,1)) { System.out.print(" Yes "); } else { System.out.print(" No "); } } }
code/data_structures/src/list/singly_linked_list/operations/find/find.py
class Node: """ A Node in a singly-linked list Parameters ------------------- data : The data to be stored in the node next: The link to the next node in the singly-linked list """ def __init__(self, data=None, next=None): self.data = data self.next = next def __repr__(self): """ Node representation as required""" return self.data class NodeAdapter1(Node): def __bool__(self): return False class NodeAdapter2(Node): def __bool__(self): return True class SinglyLinkedList: def __init__(self, NodeType): self.head = None self._NodeType = NodeType def append(self, data): """ Inserts New data at the ending of the Linked List Takes O(n) time """ new_node = self._NodeType(data=data) if self.head is None: self.head = new_node return current_node = self.head while current_node.next is not None: current_node = current_node.next current_node.next = new_node def find(self, data): """ Returns the first index at which the element is found Returns -1 if not found Takes O(n) time """ if self.head is not None: current_node = self.head index = 0 while current_node is not None: if current_node.data == data: return index current_node = current_node.next index += 1 return -1 def __repr__(self): """ Gives a string representation of the list in the given format: a -> b -> c -> d """ all_nodes = [] current_node = self.head while current_node is not None: all_nodes.append(str(current_node.data)) current_node = current_node.next if len(all_nodes) > 0: return " -> ".join(all_nodes) else: return "" def main(): lst1 = SinglyLinkedList(Node) lst1.append(10) lst1.append(20) lst1.append(30) lst1.find(10) lst2 = SinglyLinkedList(NodeAdapter1) lst2.append(10) lst2.append(20) lst2.append(30) lst2.find(20) lst3 = SinglyLinkedList(NodeAdapter2) lst3.append(10) lst3.append(20) lst3.append(30) lst3.find(30) if __name__ == "__main__": main()
code/data_structures/src/list/singly_linked_list/operations/insertion/insertion_at_end.py
# Python Utility to add element at the end of the Singly Linked List # Part of Cosmos by OpenGenus Foundation class Node: """ A Node in a singly-linked list Parameters ------------------- data : The data to be stored in the node next: The link to the next node in the singly-linked list """ def __init__(self, data=None, next=None): """ Initializes node structure""" self.data = data self.next = next def __repr__(self): """ Node representation as required""" return self.data class SinglyLinkedList: """ A structure of singly linked lists """ def __init__(self): """Creates a Singly Linked List in O(1) Time""" self.head = None def insert_in_end(self, data): """ Inserts New data at the ending of the Linked List Takes O(n) time """ if not self.head: self.head = Node(data=data) return current_node = self.head while current_node.next: current_node = current_node.next new_node = Node(data=data, next=None) current_node.next = new_node def __repr__(self): """ Gives a string representation of the list in the given format: a -> b -> c -> d """ all_nodes = [] current_node = self.head while current_node: all_nodes.append(str(current_node.data)) current_node = current_node.next if len(all_nodes) > 0: return " -> ".join(all_nodes) else: return "Linked List is empty"
code/data_structures/src/list/singly_linked_list/operations/insertion/insertion_at_front.py
# Python Utility to add element at the beginning of the Singly Linked List # Part of Cosmos by OpenGenus Foundation class Node: """ A Node in a singly-linked list Parameters ------------------- data : The data to be stored in the node next: The link to the next node in the singly-linked list """ def __init__(self, data=None, next=None): """ Initializes node structure""" self.data = data self.next = next def __repr__(self): """ Node representation as required""" return self.data class SinglyLinkedList: """ A structure of singly linked lists """ def __init__(self): """Creates a Singly Linked List in O(1) Time""" self.head = None def insert_in_front(self, data): """ Inserts New data at the beginning of the Linked List Takes O(1) time """ self.head = Node(self, data=data, next=self.head) def __repr__(self): """ Gives a string representation of the list in the given format: a -> b -> c -> d """ all_nodes = [] current_node = self.head while current_node: all_nodes.append(str(current_node.data)) current_node = current_node.next if len(all_nodes) > 0: return " -> ".join(all_nodes) else: return "Linked List is empty"
code/data_structures/src/list/singly_linked_list/operations/insertion/insertion_at_nth_node.py
# Python Utility to add element after the nth node of the Singly Linked List # Part of Cosmos by OpenGenus Foundation class Node: """ A Node in a singly-linked list Parameters ------------------- data : The data to be stored in the node next: The link to the next node in the singly-linked list """ def __init__(self, data=None, next=None): """ Initializes node structure""" self.data = data self.next = next def __repr__(self): """ Node representation as required""" return self.data class SinglyLinkedList: """ A structure of singly linked lists """ def __init__(self): """Creates a Singly Linked List in O(1) Time""" self.head = None def insert_nth(self, data, n): """ Inserts New data at the ending of the Linked List Takes O(n) time """ if not self.head: self.head = Node(data=data) return i = 1 current_node = self.head while current_node.next and i != n: current_node = current_node.next i += 1 # If nth node doesn't exist, add a node at the end if i != n and not current_node.next: current_node.next = Node(data, next=None) if i == n: rest_of_array = current_node.next new_node = Node(data, rest_of_array) current_node.next = new_node def __repr__(self): """ Gives a string representation of the list in the given format: a -> b -> c -> d """ all_nodes = [] current_node = self.head while current_node: all_nodes.append(str(current_node.data)) current_node = current_node.next if len(all_nodes) > 0: return " -> ".join(all_nodes) else: return "Linked List is empty"
code/data_structures/src/list/singly_linked_list/operations/merge_sorted/merge_sorted.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; //Merge Function for linkedlist ListNode* merge(ListNode* head1, ListNode* head2) { ListNode* head3 = NULL; ListNode* temp3 = NULL; while (head1 && head2) { if (head1->val < head2->val) { if (head3 == NULL) head3 = head1; if (temp3) temp3->next = head1; temp3 = head1; head1 = head1->next; } else { if (head3 == NULL) head3 = head2; if (temp3) temp3->next = head2; temp3 = head2; head2 = head2->next; } } if (head1) { if (head3) temp3->next = head1; else return head1; } if (head2) { if (head3) temp3->next = head2; else return head2; } return head3; } //Sort function for linkedlist following divide and conquer approach ListNode* merge_sort(ListNode* A) { if (A == NULL || A->next == NULL) return A; ListNode* temp = A; int i = 1; while (temp->next) { i++; temp = temp->next; } int d = i / 2; int k = 0; temp = A; while (temp) { k++; if (k == d) break; temp = temp->next; } ListNode* head1 = A; ListNode* head2 = temp->next; temp->next = NULL; head1 = merge_sort(head1); head2 = merge_sort(head2); ListNode* head3 = merge(head1, head2); return head3; } //function used for calling divide and xonquer algorithm ListNode* sortList(ListNode* A) { ListNode* head = merge_sort(A); return head; } int main() { ListNode* head = new ListNode(5); ListNode* temp = head; // Creating a linkedlist int i = 4; while (i > 0) //Adding values to the linkedlist { ListNode* t = new ListNode(i); temp->next = t; temp = temp->next; i--; } head = sortList(head); //calling merge_sort function return 0; }
code/data_structures/src/list/singly_linked_list/operations/nth_node_linked_list/nth_node_linked_list.c
#include <stdio.h> #include <stdlib.h> #define NUM_NODES 100 // Part of Cosmos by OpenGenus Foundation typedef struct node { int value; struct node* next; }node; node* head = NULL; node* create_node(int val) { node *tmp = (node *) malloc(sizeof(node)); tmp->value = val; tmp->next = NULL; return tmp; } void create_list(int val) { static node* tmp = NULL; if (!head) { head = create_node(val); tmp = head; } else { tmp->next = create_node(val); tmp = tmp->next; } } node* ptr = NULL; void get_nth_node(int node_num,node* curr) { static int ctr = 0; if (curr->next) { get_nth_node(node_num,curr->next ); } ctr++; if (ctr == node_num) ptr = curr; } void cleanup_list() { node* tmp = NULL; while (head->next) { tmp = head; head = head->next; free(tmp); } free(head); head = NULL; } int main() { int node_num,ctr; node* tmp = NULL; printf("Enter node number\n"); scanf("%d",&node_num); for (ctr = 0; ctr < NUM_NODES; ctr++) create_list(ctr); get_nth_node(node_num, head); if ((node_num > 0) && (node_num <= NUM_NODES)) printf("curr->value = %d\n",ptr->value); else printf("node number has to be greater than 0\n"); cleanup_list(); return 0; }
code/data_structures/src/list/singly_linked_list/operations/nth_node_linked_list/nth_node_linked_list.cpp
/// /// Part of Cosmos by OpenGenus Foundation /// Contributed by: Pranav Gupta (foobar98) /// Print Nth node of a singly linked list in the reverse manner /// #include <iostream> using namespace std; // Linked list node struct Node { public: int data; Node *next; Node(int data) { this->data = data; next = NULL; } }; // Create linked list of n nodes Node* takeInput(int n) { // n is the number of nodes in linked list Node *head = NULL, *tail = NULL; int i = n; cout << "Enter elements: "; while (i--) { int data; cin >> data; Node *newNode = new Node(data); if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } } return head; } // To find length of linked list int length(Node *head) { int l = 0; while (head != NULL) { head = head->next; l++; } return l; } void printNthFromEnd(Node *head, int n) { // Get length of linked list int len = length(head); // check if n is greater than length if (n > len) return; // nth from end = (len-n+1)th node from beginning for (int i = 1; i < len - n + 1; i++) head = head->next; cout << "Nth node from end: " << head->data << endl; } int main() { cout << "Enter no. of nodes in linked list: "; int x; cin >> x; Node *head = takeInput(x); cout << "Enter n (node from the end): "; int n; cin >> n; printNthFromEnd(head, n); }
code/data_structures/src/list/singly_linked_list/operations/print_reverse/print_reverse.py
# Part of Cosmos by OpenGenus Foundation class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node size = 0 def returnsize(root): i = 0 while root: root = root.next_node i += 1 return i def insertatbeg(d, root): newnode = Node(d, None) if root: newnode.next_node = root root.size += 1 return newnode def insertatend(d, root): pre = root newnode = Node(d, None) if root: root.size += 1 i = 0 while root: pre = root root = root.next_node i += 1 pre.next_node = newnode else: root = newnode root = insertatbeg(910, None) root = insertatbeg(90, root) root = insertatbeg(80, root) insertatend(2, root) insertatend(27, root) insertatend(17, root) insertatend(37, root) insertatend(47, root) insertatend(57, root) root = insertatbeg(90, root) root = insertatbeg(80, root) insertatend(47, root) insertatend(57, root) print(returnsize(root)) print(root.size) def printlinklist(root): while root: print(root.data, end=" ") root = root.next_node def printlinklist_in_reverse_order(root): if root != None: printlinklist_in_reverse_order(root.next_node) print(root.data, end=" ") printlinklist(root) print() printlinklist_in_reverse_order(root)
code/data_structures/src/list/singly_linked_list/operations/print_reverse/print_reverse.scala
//Part of Cosmos by OpenGenus Foundation object PrintReverse { case class Node[T](value: T, next: Option[Node[T]]) { // append new node at the end def :~>(tail: Node[T]): Node[T] = next match { case None => new Node(value, Some(tail)) case Some(x) => new Node(value, Some(x :~> tail)) } } object Node { def apply[T](value: T): Node[T] = new Node(value, None) } def printReverse[T](node: Node[T]): Unit = { node.next.foreach(printReverse) println(node.value) } def main(args: Array[String]): Unit = { val integerLinkedList = Node(1) :~> Node(2) :~> Node(3) val stringLinkedList = Node("hello") :~> Node("world") :~> Node("good") :~> Node("bye") printReverse(integerLinkedList) printReverse(stringLinkedList) } }