filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/data_structures/src/list/singly_linked_list/operations/push/push.cpp
#include <iostream> using namespace std; // Everytime you work with Append or Push function, there is a corner case. // When a NULL Node is passed you have to return a Node that points to the given value. // There are two ways to achieve this: // 1. Receive the double pointer as an argument. // 2. Return the new Node. struct Node { int data; Node* next; }; void printList( Node *head) { while (head) { cout << head->data << " "; head = head->next; } cout << endl; } void push( Node** headref, int x) { Node* head = *headref; Node* newNode = new Node(); newNode->data = x; newNode->next = head; *headref = newNode; } void pushAfter(Node* prev_Node, int data) { Node* newNode = new Node(); newNode->data = data; newNode->next = prev_Node->next; prev_Node->next = newNode; } void append( Node** headref, int x) { Node* head = *headref; if (head == nullptr) { Node* newNode = new Node(); newNode->data = x; newNode->next = nullptr; *headref = newNode; return; } while (head->next) head = head->next; Node *temp = new Node(); head->next = temp; temp->data = x; } int main() { Node *head = nullptr; append(&head, 5); append(&head, 10); push(&head, 2); pushAfter(head->next, 4); printList(head); return 0; }
code/data_structures/src/list/singly_linked_list/operations/reverse/reverse.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> 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; } } void print_list(node* tmp) { while (tmp) { printf("%d ", tmp->value); tmp = tmp->next; } printf("\n"); } void reverse_list() { node* trail_ptr = head; node* tmp = trail_ptr->next; node* lead_ptr = tmp; if (!tmp) return; while (lead_ptr->next) { lead_ptr = lead_ptr->next; if (lead_ptr) { tmp->next = trail_ptr; if (trail_ptr == head) head->next = NULL; trail_ptr = tmp; tmp = lead_ptr; } } tmp->next = trail_ptr; if (trail_ptr == head) trail_ptr->next = NULL; trail_ptr = tmp; if (lead_ptr != tmp) lead_ptr->next = tmp; if (lead_ptr) head = lead_ptr; } void cleanup_list() { node* tmp = NULL; while (head->next) { tmp = head; head = head->next; free(tmp); } free(head); head = NULL; } int main() { int num_nodes, value, ctr; printf("Enter number of nodes\n"); scanf("%d",&num_nodes); for (ctr = 0; ctr < num_nodes; ctr++) { printf("Enter value\n"); scanf("%d",&value); create_list(value); } print_list(head); reverse_list(); print_list(head); cleanup_list(); return 0; }
code/data_structures/src/list/singly_linked_list/operations/reverse/reverse.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) { } }; // Reverse function for linkedlist ListNode* reverseList(ListNode* A) { ListNode* prev = NULL; while (A && A->next) { ListNode* temp = A->next; A->next = prev; prev = A; A = temp; } A->next = prev; return A; } 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 = reverseList(head); //calling reverse function return 0; }
code/data_structures/src/list/singly_linked_list/operations/reverse/reverse_iteration.cpp
#include <iostream> using namespace std; struct node { int data; struct node * next; }*head; void reverse() { node *prev = NULL; node *cur = head; node *next; while (cur != NULL) { next = cur->next; cur->next = prev; prev = cur; cur = next; } head = prev; } void push(int x) { node *ptr = new node; ptr->data = x; ptr->next = NULL; if (head == NULL) head = ptr; else { ptr->next = head; head = ptr; } } void print() { node *ptr = head; while (ptr != NULL) { cout << ptr->data << " "; ptr = ptr->next; } } int main() { push(2); push(3); push(4); push(5); cout << "\nOriginal list is : "; print(); cout << "\nReversed list is : "; reverse(); print(); cout << "\n"; return 0; }
code/data_structures/src/list/singly_linked_list/operations/reverse/reverse_recursion.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; class node { public: int data; node* next; public: node(int d) { data = d; next = nullptr; } }; void print(node*head) { while (head != nullptr) { cout << head->data << "-->"; head = head->next; } } void insertAtHead(node*&head, int d) { node* n = new node(d); n->next = head; head = n; } void insertInMiddle(node*&head, int d, int p) { if (p == 0) insertAtHead(head, d); else { //assuming p<=length of LL node*temp = head; for (int jump = 1; jump < p; jump++) temp = temp->next; node*n = new node(d); n->next = temp->next; temp->next = n; } } void takeInput(node*&head) { int d; cin >> d; while (d != -1) { insertAtHead(head, d); cin >> d; } } ///overloading to print LL ostream& operator<<(ostream&os, node*head) { print(head); cout << endl; return os; } istream& operator>>(istream&is, node*&head) { takeInput(head); return is; } ///optimized recursive reverse node*recReverse2(node*head) { if (head == nullptr || head->next == nullptr) return head; node*newHead = recReverse2(head->next); head->next->next = head; head->next = nullptr; return newHead; } int main() { node*head = nullptr; cin >> head; cout << head; head = recReverse2(head); cout << "Reversed linked list: " << endl; cout << head; return 0; }
code/data_structures/src/list/singly_linked_list/operations/reverse/reverse_recursion2.cpp
#include <iostream> using namespace std; struct Node { int data; struct Node* next; }; void printReverse(struct Node* head) { if (head == NULL) return; printReverse(head->next); cout << head->data << " "; } void push(struct Node** head_ref, char new_data) { struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } int main() { struct Node* head = NULL; for (int i = 0; i < 10; i++) push(&head, i); printReverse(head); return 0; }
code/data_structures/src/list/singly_linked_list/operations/rotate/rotate.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; ListNode* rotate(ListNode* A, int B) { int t = 0; ListNode* temp = A; ListNode* prev2 = NULL; while (temp) { ++t; prev2 = temp; temp = temp->next; } B = B % t; //count by which the list is to be rotated if (B == 0) return A; int p = t - B; ListNode* prev = NULL; ListNode* head = A; temp = A; for (int i = 1; i < p; i++) //reaching that point from where the list is to be rotated { prev = temp; temp = temp->next; } prev = temp; if (temp && temp->next) //rotating the list temp = temp->next; if (prev2) prev2->next = A; if (prev) prev->next = NULL; head = temp; return head; } int main() { using namespace std; 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 = rotate(head, 2); //calling rotate function return 0; }
code/data_structures/src/list/singly_linked_list/operations/rotate_a_linked_list_by_k_nodes/rotate_a_linked_list_by_k_nodes.cpp
// C++ program to rotate a linked list counter clock wise by k Nodes // where k can be greater than length of linked list #include <iostream> class Node { public: int data; Node *next; Node(int d): next(nullptr),data(d) { } }; Node *insert() { // no. of values to insert std::cout << "Enter no. of Nodes you want to insert in linked list: \n"; int n; std::cin >> n; Node *head = nullptr; Node *temp = head; std::cout << "Enter " << n << " values of linked list : \n"; for (int i = 0; i < n; ++i) { int value; std::cin >> value; if (i == 0) { // insert at head head = new Node(value); temp = head; continue; } else { temp->next = new Node(value); temp = temp->next; } } return head; } Node *rotate(Node *head, int k) { // first check whether k is small or greater than length of linked list // so first find length of linked list int len = 0; Node *temp = head; while (temp != nullptr) { temp = temp->next; len++; } // length of linked list = len // update k according to length of linked list // because k can be greater than length of linked list k %= len; if (k == 0) { // since when k is multiple of len its mod becomes zero // so we have to correct it k = len; } if (k == len) { // since if k==len then even after rotating it linked list will remain same return head; } int count = 1; temp = head; while (count < k and temp != nullptr) { temp = temp->next; count++; } Node *newHead = temp->next; temp->next = nullptr; temp = newHead; while (temp->next != nullptr) { temp = temp->next; } temp->next = head; return newHead; } void printList(Node *head) { Node *temp = head; while (temp != nullptr) { std::cout << temp->data << " --> "; temp = temp->next; } std::cout << "nullptr \n"; return; } int main() { Node *head = insert(); printList(head); std::cout << "Enter value of k: \n"; int k; std::cin >> k; head = rotate(head, k); std::cout << "After rotation : \n"; printList(head); return 0; } // Input and Output : /* Enter no. of Nodes you want to insert in linked list: 9 Enter 9 values of linked list : 1 2 3 4 5 6 7 8 9 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> nullptr Enter value of k: 3 After rotation : 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> 1 --> 2 --> 3 --> nullptr */
code/data_structures/src/list/singly_linked_list/operations/sort/bubble_sort.cpp
///Bubble sort a linked list #include <iostream> #include <stack> using namespace std; class node { public: int data; node* next; public: node(int d) { data = d; next = NULL; } }; void print(node*head) { while (head != NULL) { cout << head->data << "-->"; head = head->next; } } void insertAtHead(node*&head, int d) { node* n = new node(d); n->next = head; head = n; } void insertInMiddle(node*&head, int d, int p) { if (p == 0) insertAtHead(head, d); else { //assuming p<=length of LL int jump = 1; node*temp = head; while (jump <= p - 1) { jump++; temp = temp->next; } node*n = new node(d); n->next = temp->next; temp->next = n; } } void takeInput(node*&head) { int d; cin >> d; while (d != -1) { insertAtHead(head, d); cin >> d; } } ///overloading to print LL ostream& operator<<(ostream&os, node*head) { print(head); cout << endl; return os; } istream& operator>>(istream&is, node*&head) { takeInput(head); return is; } int length(node*head) { int len = 0; while (head != NULL) { len++; head = head->next; } return len; } void bubbleSort(node*&head) { int n = length(head); for (int i = 0; i < n - 1; i++) //n-1 times { node*current = head; node*prev = NULL; node*next; while (current != NULL && current->next != NULL) { if (current->data > current->next->data) { //swapping if (prev == NULL) { next = current->next; current->next = next->next; next->next = current; head = next; prev = next; } else { next = current->next; prev->next = next; current->next = next->next; next->next = current; prev = next; } } else { prev = current; current = current->next; } } } } int main() { node*head = NULL; cin >> head; cout << head; bubbleSort(head); cout << "BUBBLE SORTED LINKED LIST" << endl; cout << head; return 0; }
code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_list.java
// Part of Cosmos by OpenGenus Foundation public class LinkedList { private class Node { int data; Node next; public Node() { } } private Node head; private Node tail; private int size; public int size() { return this.size; } public boolean isEmpty() { return this.size == 0; } public void display() { Node temp; temp = head; System.out.println("------------------------------------------"); while (temp != null) { System.out.print(temp.data + "\t"); temp = temp.next; } System.out.println("."); System.out.println("--------------------------------------------"); } public int getfirst() throws Exception { if (this.size == 0) { throw new Exception("LinkedList is empty"); } return this.head.data; } public int getLast() throws Exception { if (this.size == 0) { throw new Exception("LinkedList is empty"); } return this.tail.data; } public int getAt(int idx) throws Exception { if (this.size == 0) { throw new Exception("LinkedList is empty"); } if (idx < 0 || idx >= this.size) { throw new Exception("index out of bound"); } Node temp = head; for (int i = 0; i < idx; i++) { temp = temp.next; } return temp.data; } public void addLast(int data) { Node nn = new Node(); nn.data = data; nn.next = null; if (this.size == 0) { this.head = nn; this.tail = nn; } else { this.tail.next = nn; this.tail = nn; } this.size++; } public void addfirst(int data) { Node nn = new Node(); nn.data = data; if (this.size == 0) { this.head = nn; this.tail = nn; } else { nn.next = this.head; this.head = nn; } this.size++; } private Node getnodeAt(int idx) throws Exception { if (this.size == 0) { throw new Exception("LinkedList is empty"); } if (idx < 0 || idx >= this.size) { throw new Exception("index out of bound"); } Node temp = head; for (int i = 0; i < idx; i++) { temp = temp.next; } return temp; } public void addAt(int data, int idx) throws Exception { Node nn = new Node(); nn.data = data; if (idx < 0 || idx > this.size) { throw new Exception("index out of bound"); } if (idx == 0) { this.addfirst(data); } else if (idx == this.size) { this.addLast(data); } else { Node nm = this.getnodeAt(idx - 1); Node np1 = nm.next; nn.next = np1; nm.next = nn; } this.size++; } public int removeFirst() throws Exception { if (this.size == 0) { throw new Exception("LinkedList is empty"); } int rv = this.head.data; if (this.size == 1) { this.head = null; this.tail = null; } else { this.head = this.head.next; } this.size--; return rv; } public int removelast() throws Exception { if (this.size == 0) { throw new Exception("LinkedList is empty"); } int rv = this.tail.data; if (this.size == 1) { this.head = null; this.tail = null; } else { Node nm = this.getnodeAt(this.size - 2); nm.next = null; this.tail = nm; } this.size--; return rv; } public int removeAt(int idx) throws Exception { { if (this.size == 0) { throw new Exception("LinkedList is empty"); } if (idx < 0 || idx > this.size) { throw new Exception("index out of bound"); } int rv = 0; if (this.size == 1) { this.head = null; this.tail = null; } if (idx == 0) { this.removeFirst(); } else if (idx == this.size) { this.removelast(); } else { Node nm = this.getnodeAt(idx - 1); Node n = nm.next; rv = n.data; Node nm1 = this.getnodeAt(idx + 1); nm.next = nm1; } this.size--; return rv; } } public void displayreverse() throws Exception { int i = this.size - 1; while (i >= 0) { System.out.print(this.getAt(i) + "\t"); i--; } } // o(n^2) public void reverselistDI() throws Exception { int left = 0; int right = this.size - 1; while (left < right) { Node leftnode = this.getnodeAt(left); Node rightnode = this.getnodeAt(right); int temp = leftnode.data; leftnode.data = rightnode.data; rightnode.data = temp; left++; right--; } } // o(n) public void reverselistPI() { Node prev = this.head; Node curr = prev.next; while (curr != null) { Node tc = curr; Node tp = prev; prev = curr; curr = curr.next; tc.next = tp; } Node temp = this.head; this.head = this.tail; this.tail = temp; } // o(n) public void reverselistPR() { reverselistPR_RH(this.head, this.head.next); Node temp = this.head; this.head = this.tail; this.tail = temp; this.tail.next = null; } private void reverselistPR_RH(Node prev, Node curr) { if (curr == null) { return; } reverselistPR_RH(curr, curr.next); curr.next = prev; } // o(n) public void reverselistDR() { // this.reverselistDR(this.head,this.head,0); HeapMover left = new HeapMover(); left.node = this.head; reverselistDR1(left, head, 0); } private Node reverselistDR(Node left, Node right, int floor) { if (right == null) { return left; } left = reverselistDR(left, right.next, floor + 1); if (floor > this.size / 2) { int temp = right.data; right.data = left.data; left.data = temp; } return left.next; } private void reverselistDR1(HeapMover left, Node right, int floor) { if (right == null) { return; } reverselistDR1(left, right.next, floor + 1); if (floor > this.size / 2) { int temp = right.data; right.data = left.node.data; left.node.data = temp; } left.node = left.node.next; } private class HeapMover { Node node; } public void fold() { HeapMover left = new HeapMover(); left.node = this.head; fold(left, this.head, 0); if (this.size % 2 == 1) { this.tail = left.node; } else { this.tail = left.node.next; } this.tail.next = null; } private void fold(HeapMover left, Node right, int floor) { if (right == null) { return; } fold(left, right.next, floor + 1); Node temp1 = null; // if() if (floor > this.size / 2) { temp1 = left.node.next; left.node.next = right; right.next = temp1; left.node = temp1; } } public int mid() { return this.midNode().data; } private Node midNode() { Node slow = this.head; Node fast = this.head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } public int kth(int k) { return this.kthNode(k).data; } private Node kthNode(int k) { Node slow = this.head; Node fast = this.head; for (int i = 0; i < k; i++) { slow = slow.next; fast = fast.next.next; } while (fast != null) { slow = slow.next; fast = fast.next; } return slow; } public void removeduplicate() { Node t1 = this.head; Node t2 = this.head; int count = 0; while (t2.next != null) { while (t2.data == t1.data && t1.next != null) { t1 = t1.next; if (t2.data == t1.data) { this.size--; } } if (t1.next == null) { t2.next = null; } else { t2.next = t1; t2 = t1; } } } // public void kreverse(int k) { // Node left = this.head; // Node right = this.head; // Node temp = this.head; // for (int i = 1; i <= this.size; i += k) { // left = right; // temp = left.next.next; // right = left.next; // for (int j = 1; j <= k; j++) { // Node tc = curr; // Node tp = prev; // // prev = curr; // curr = curr.next; // tc.next = tp; // // } // // } // // } public LinkedList mergetwosortedLinkedList(LinkedList other) { Node ttemp = this.head; Node otemp = other.head; LinkedList rv = new LinkedList(); while (ttemp != null && otemp != null) { if (ttemp.data < otemp.data) { rv.addLast(ttemp.data); ttemp = ttemp.next; } else { rv.addLast(otemp.data); otemp = otemp.next; } } while (ttemp != null) { rv.addLast(ttemp.data); ttemp = ttemp.next; } while (otemp != null) { rv.addLast(otemp.data); otemp = otemp.next; } return rv; } public void mergesort() { if (this.size == 1) return; LinkedList gh = new LinkedList(); LinkedList lh = new LinkedList(); Node mid = this.midNode(); Node temp = mid.next; gh.head = this.head; gh.tail = mid; gh.tail.next = null; gh.size = (this.size + 1) / 2; lh.head = temp; lh.tail = this.tail; lh.tail.next = null; lh.size = this.size / 2; LinkedList merged = new LinkedList(); gh.mergesort(); lh.mergesort(); merged = gh.mergetwosortedLinkedList(lh); this.head = merged.head; this.tail = merged.tail; this.size = merged.size; } public LinkedList KREVERSE(int k) throws Exception{ LinkedList pre=new LinkedList(); LinkedList cur; while(this.size()!=0){ cur=new LinkedList(); for(int i=0;i<k;i++){ int rv=this.removeFirst(); cur.addfirst(rv); } if(pre.isEmpty()) pre=cur; else{ pre.tail.next=cur.head; pre.tail=cur.tail; pre.size+=cur.size(); } } return pre; } public void removeduplicat() throws Exception{ LinkedList n=new LinkedList(); while(this.size()!=0){ int data=this.removeFirst(); if(n.isEmpty()){ n.addLast(data); } if(n.getLast()!=data){ n.addLast(data); } } this.head=n.head; this.tail=n.tail; this.size=n.size; } }
code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_list_example.java
import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Scanner; public class LinkedListeg { class Node { int value; Node next = null; Node(int value) { this.value = value; } } protected Node head = null; protected Node tail = null; public void addToFront(int value) { Node newNode = new Node(value); newNode.next = head; head = newNode; if(newNode.next == null) { tail = newNode; } } public void addToBack(int value) { Node newNode = new Node(value); if(tail == null) { head = newNode; } else { tail.next = newNode; } tail = newNode; } public void addAtIndex(int index,int value) { if(index < 0) { throw new IndexOutOfBoundsException(); } else if(index == 0) { addToFront(value); } else { Node newNode = new Node(value); Node current = head; for(int i = 0; i < index-1; i++) { if(current == null) { throw new IndexOutOfBoundsException(); } current = current.next; } if(current.next == null) { tail = newNode; } else { newNode.next = current.next; current.next = newNode; } } } public void removeFromFront() { if(head != null) { head = head.next; } if(head == null) { tail = null; } } public void removeFromBack() { if(head == null) { return; } else if(head.equals(tail)) { head = null; tail = null; } else { Node current = head; while(current.next != tail) { current = current.next; } tail = current; current.next = null; } } public void removeAtIndex(int index) { if(index < 0) { throw new IndexOutOfBoundsException(); } else if(index == 0) { removeFromFront(); } else { Node current = head; for(int i = 0; i < index-1; i++) { if(current == null) { throw new IndexOutOfBoundsException(); } current = current.next; } current.next = current.next.next; if(current.next == null) { tail = current; } } } public void printList() { Node newNode = head; if(head != null) { System.out.println("The Linked List contains :"); while(newNode != null) { System.out.println(newNode.value); newNode = newNode.next; } } else { System.out.println("The list contains no elements"); } } public void count() { Node newNode=head; int counter = 0; while(newNode != null ) { counter++; newNode = newNode.next; } System.out.println("The list contains "+counter+" elements"); } public static void main(String[] args) { Scanner in=new Scanner(new InputStreamReader(System.in)); LinkedListeg list = new LinkedListeg(); int ch = 0; do { System.out.println("Choose form the following"); System.out.println("1.Add to Front\n2.Add to Back\n3.Add at index\n4.Remove from front"); System.out.println("5.Remove from back\n6.remove at index\n7.Print elements in the Linked List"); System.out.println("8.Count number of elements in the list\n9.Exit"); ch = in.nextInt(); int value = 0; int index = 0; switch (ch) { case 1: System.out.println("Enter a value"); value = in.nextInt(); list.addToFront(value); break; case 2: System.out.println("Enter a value"); value = in.nextInt(); list.addToBack(value); break; case 3: System.out.println("Enter a value"); value = in.nextInt(); System.out.println("Enter index"); index = in.nextInt(); list.addAtIndex(index,value); break; case 4: list.removeFromFront(); break; case 5: list.removeFromBack(); break; case 6: System.out.println("Enter the index"); index = in.nextInt(); list.removeAtIndex(index); break; case 7: list.printList(); break; case 8: list.count(); break; case 9: System.exit(0); break; default: System.out.println("Wrong Choice"); break; } System.out.println(); } while (ch != 9); } }
code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_list_operations.cpp
#include <iostream> using namespace std; //built node .... node = (data and pointer) struct node { int data; //data item node* next; //pointer to next node }; //built linked list class linkedlist { private: node* head; //pointer to the first node public: linkedlist() //constructor { head = NULL; //head pointer points to null in the beginning == empty list } //declaration void addElementFirst(int d); //add element in the beginning (one node) void addElementEnd(int d); //add element in the end (one node) void addElementAfter(int d, int b); //add element d before node b void deleteElement(int d); void display(); //display all nodes }; //definition //1-Push front code void linkedlist::addElementFirst(int d) { node* newNode = new node; newNode->data = d; newNode->next = head; head = newNode; } //2-Push back code void linkedlist::addElementEnd(int x) { node* newNode = new node; node* temp = new node; temp = head; newNode->data = x; if (temp == NULL) { newNode->next = NULL; head = newNode; return; } while (temp->next != NULL) temp = temp->next; newNode->next = NULL; temp->next = newNode; } //3-Push after code //head->10->5->8->NULL //if d=5,key=2 //head->10->5->2->8->NULL void linkedlist::addElementAfter(int d, int key) { node* search = new node; //search is pointer must search to points to the node that we want search = head; //firstly search must points to what head points while (search != NULL) //if linked list has nodes and is not empty { if (search->data == d) { node* newNode = new node; newNode->data = key; //put key in data in newNode newNode->next = search->next; //make the next of newNode pointer to the next to search pointer search->next = newNode; //then make search pointer to the newNode return; //or break; } //else search = search->next; } if (search == NULL) //if linked list empty cout << "The link not inserted because there is not found the node " << d << " in the LinkedList. " << endl; } //4-delete code void linkedlist::deleteElement(int d) { node* del; del = head; if (del == NULL) { cout << "Linked list is empty" << endl; return; } if (del->data == d) //if first element in linked list is the element that we want to delete ... or one element is what we want { head = del->next; //make head points to the next to del return; } //if(del->data!=d) .... the same if (del->next == NULL) { cout << "Is not here, So not deleted." << endl; return; } //if here more one nodes...one node points to another node ... bigger than 2 nodes .. at least 2 nodes while (del->next != NULL) { if (del->next->data == d) { node* tmp = del->next; del->next = del->next->next; delete tmp; return; } //else del = del->next; } cout << "Is not here, So not deleted." << endl; } //void linkedlist::display(node *head) void linkedlist::display() { int n = 0; //counter for number of node node* current = head; if (current == NULL) cout << "This is empty linked list." << endl; while (current != NULL) { cout << "The node data number " << ++n << " is " << current->data << endl; current = current->next; } cout << endl; } int main() { linkedlist li; li.display(); li.addElementFirst(25); //head->25->NULL li.addElementFirst(36); //head->36->25->NULL li.addElementFirst(49); //head->49->36->25->NULL li.addElementFirst(64); //head->64->49->36->25->NULL cout << "After adding in the first of linked list" << endl; li.display(); //64 //49 //36 //25 cout << endl; cout << "After adding in the end of linked list" << endl; //head->64->49->36->25->NULL li.addElementEnd(25); //head->25->NULL li.addElementEnd(36); //head->25->36->NULL li.addElementEnd(49); //head->25->36->49->NULL li.addElementEnd(64); //head->25->36->49->64->NULL //head->64->49->36->25->25->36->49->64->NULL li.display(); cout << endl; //head->64->49->36->25->25->36->49->64->NULL cout << "linked list after adding 10 after node that has data = 49" << endl; li.addElementAfter(49, 10); li.display(); //head->64->49->10->36->25->25->36->49->64->NULL //head->64->49->10->36->25->25->36->49->64->NULL cout << "linked list after adding deleting 49" << endl; li.deleteElement(49); li.display(); //head->64->10->36->25->25->36->49->64->NULL //Notice :delete the first 49 ... not permission for duplicates return 0; }
code/data_structures/src/list/singly_linked_list/operations/unclassified/union_intersection_in_list.c
// C/C++ program to find union and intersection of two unsorted // linked lists // Part of Cosmos by OpenGenus Foundation #include<stdio.h> #include<stdlib.h> #include<conio.h> /* Link list node */ struct Node { int data; struct Node* next; }; /* A utility function to insert a node at the beginning of a linked list*/ void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */ bool isPresent(struct Node *head, int data); /* Function to get union of two linked lists head1 and head2 */ struct Node *getUnion(struct Node *head1, struct Node *head2) { struct Node *result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 which are not // present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result; } /* Function to get intersection of two linked lists head1 and head2 */ struct Node *getIntersection(struct Node *head1, struct Node *head2) { struct Node *result = NULL; struct Node *t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push (&result, t1->data); t1 = t1->next; } return result; } /* A utility function to insert a node at the begining of a linked list*/ void push (struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* A utility function to print a linked list*/ void printList (struct Node *node) { while (node != NULL) { printf ("%d ", node->data); node = node->next; } } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent (struct Node *head, int data) { struct Node *t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0; } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lits 10->15->5->20 */ push (&head1, 20); push (&head1, 4); push (&head1, 15); push (&head1, 10); /*create a linked lits 8->4->2->10 */ push (&head2, 10); push (&head2, 2); push (&head2, 4); push (&head2, 8); intersecn = getIntersection (head1, head2); unin = getUnion (head1, head2); printf ("\nFirst list is \n"); printList (head1); printf ("\nSecond list is \n"); printList (head2); printf ("\nIntersection list is \n"); printList (intersecn); printf ("\nUnion list is \n"); printList (unin); getch(); return 0; }
code/data_structures/src/list/singly_linked_list/singly_linked_list.c
#ifndef _LINKED_LIST_C_ #define _LINKED_LIST_C_ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> /* C99 required */ typedef bool (*compare_func)(void* p_data1, void* p_data2); typedef void (*traverse_func)(void *p_data); typedef void (*destroy_func)(void* p_data); typedef struct linked_list_node { struct linked_list_node* p_next; void* p_data; } linked_list_node, *p_linked_list_node; typedef struct linked_list { linked_list_node* p_head; linked_list_node* p_tail; linked_list_node* p_cur; unsigned int u_count; } linked_list, *p_linked_list; linked_list* linked_list_create(); void linked_list_destroy(linked_list* p_linked_list, destroy_func destroy_func); bool linked_list_delete(linked_list* p_linked_list, void* p_match_data, compare_func compare_func, destroy_func destroy_func); void* linked_list_get_at(linked_list* p_linked_list, unsigned int u_index); bool linked_list_traverse(linked_list* p_linked_list, traverse_func traverse_func); unsigned int linked_list_get_count(linked_list* p_linked_list); void linked_list_begin(linked_list* p_linked_list); void* linked_list_next(linked_list* p_linked_list); void* linked_list_get_head(linked_list* p_linked_list); void* linked_list_get_tail(linked_list* p_linked_list); void* linked_list_get_cursor(linked_list* p_linked_list); void* linked_list_pop_head(linked_list* p_linked_list); void* linked_list_pop_tail(linked_list* p_linked_list); bool linked_list_insert_head(linked_list* p_linked_list, void* p_data); bool linked_list_insert_tail(linked_list* p_linked_list, void* p_data); linked_list* linked_list_create() { linked_list* p_linked_list; p_linked_list = (linked_list*)malloc(sizeof(linked_list)); if (p_linked_list != NULL) { p_linked_list->p_cur = NULL; p_linked_list->p_head = NULL; p_linked_list->p_tail = NULL; p_linked_list->u_count = 0; } return p_linked_list; } void linked_list_destroy(linked_list* p_linked_list, destroy_func destroy_func) { linked_list_node* p_node; if (p_linked_list) { p_node = p_linked_list->p_head; while (p_node != NULL) { linked_list_node* p_del_node; p_del_node = p_node; p_node = p_node->p_next; if (destroy_func != NULL && p_del_node->p_data != NULL) { (*destroy_func)(p_del_node->p_data); } free(p_del_node); } free(p_linked_list); } } bool linked_list_insert_head(linked_list* p_linked_list, void* p_data) { linked_list_node* p_node; if (p_linked_list == NULL || p_data == NULL) { return false; } p_node = (linked_list_node*)malloc(sizeof(linked_list_node)); if (p_node == NULL) { return false; } p_node->p_data = p_data; p_node->p_next = p_linked_list->p_head; p_linked_list->p_head = p_node; if (p_linked_list->p_tail == NULL) { p_linked_list->p_tail = p_node; } p_linked_list->u_count++; return true; } bool linked_list_insert_tail(linked_list* p_linked_list, void* p_data) { linked_list_node* p_node; if (p_linked_list == NULL || p_data == NULL) { return false; } p_node = (linked_list_node*)malloc(sizeof(linked_list_node)); if (p_node == NULL) { return false; } p_node->p_data = p_data; p_node->p_next = NULL; if (p_linked_list->p_tail == NULL) { p_linked_list->p_tail = p_node; p_linked_list->p_head = p_node; } else { p_linked_list->p_tail->p_next = p_node; p_linked_list->p_tail = p_node; } p_linked_list->u_count++; return true; } void* linked_list_pop_head(linked_list* p_linked_list) { linked_list_node* p_pop_node; void* p_pop_data; if (p_linked_list == NULL || p_linked_list->p_head == NULL) { return NULL; } p_pop_node = p_linked_list->p_head; p_pop_data = p_pop_node->p_data; if (p_linked_list->p_cur == p_linked_list->p_head) { p_linked_list->p_cur = p_linked_list->p_head->p_next; } p_linked_list->p_head = p_linked_list->p_head->p_next; p_linked_list->u_count--; if (p_linked_list->u_count == 0) { p_linked_list->p_tail = NULL; } free(p_pop_node); return p_pop_data; } void* linked_list_pop_tail(linked_list* p_linked_list) { linked_list_node* p_pop_node; linked_list_node* p_tail_prev_node; void* p_pop_data; if (p_linked_list == NULL || p_linked_list->p_head == NULL) { return NULL; } p_pop_node = p_linked_list->p_tail; p_pop_data = p_pop_node->p_data; p_tail_prev_node = p_linked_list->p_head; if (p_linked_list->p_tail == p_linked_list->p_head) { p_tail_prev_node = NULL; p_linked_list->p_head = NULL; } else { while (p_tail_prev_node != NULL) { if (p_tail_prev_node->p_next == p_linked_list->p_tail) { break; } p_tail_prev_node = p_tail_prev_node->p_next; } } if (p_linked_list->p_cur == p_linked_list->p_tail) { p_linked_list->p_cur = p_tail_prev_node; } p_linked_list->p_tail = p_tail_prev_node; if (p_tail_prev_node != NULL) { p_tail_prev_node->p_next = NULL; } p_linked_list->u_count--; free(p_pop_node); return p_pop_data; } bool linked_list_delete(linked_list* p_linked_list, void* p_match_data, compare_func compare_func, destroy_func destroy_func) { linked_list_node* p_node; linked_list_node* p_prev_node; if (p_linked_list == NULL || compare_func == NULL) { return false; } p_node = p_linked_list->p_head; p_prev_node = p_node; while (p_node != NULL) { if ((*compare_func)(p_node->p_data, p_match_data) == 0) { if (p_prev_node == p_node) { p_linked_list->p_head = p_node->p_next; if (p_linked_list->p_tail == p_node) { p_linked_list->p_tail = NULL; p_linked_list->p_cur = NULL; } } else { p_prev_node->p_next = p_node->p_next; if (p_linked_list->p_tail == p_node) { p_linked_list->p_tail = p_prev_node; } if (p_linked_list->p_cur == p_node) { p_linked_list->p_cur = p_node->p_next; } } if (destroy_func != NULL && p_node->p_data != NULL) { (*destroy_func)(p_node->p_data); } free(p_node); break; } p_prev_node = p_node; p_node = p_node->p_next; } return true; } void* linked_list_get_at(linked_list* p_linked_list, unsigned int u_index) { unsigned int i; linked_list_node* p_node; if (p_linked_list == NULL || p_linked_list->u_count >= u_index) { return NULL; } p_node = p_linked_list->p_head; for (i = 0; i < u_index; i++) { p_node = p_node->p_next; } return p_node->p_data; } unsigned int linked_list_get_count(linked_list* p_linked_list) { if (p_linked_list == NULL) { return (0); } return p_linked_list->u_count; } void* linked_list_get_head(linked_list* p_linked_list) { if (p_linked_list == NULL) { return NULL; } if (p_linked_list->p_head == NULL) { return NULL; } return p_linked_list->p_head->p_data; } void* linked_list_get_cursor(linked_list* p_linked_list) { if (p_linked_list == NULL) { return NULL; } if (p_linked_list == NULL) { return NULL; } return p_linked_list->p_cur->p_data; } void* linked_list_get_tail(linked_list* p_linked_list) { if (p_linked_list == NULL) { return NULL; } if (p_linked_list->p_tail != NULL) { return p_linked_list->p_tail->p_data; } else { return NULL; } } void linked_list_begin(linked_list* p_linked_list) { p_linked_list->p_cur = p_linked_list->p_head; return; } void* linked_list_next(linked_list* p_linked_list) { linked_list_node* p_cur; p_cur = p_linked_list->p_cur; if (p_cur == NULL) { p_linked_list->p_cur = p_cur->p_next; return p_cur->p_data; } return NULL; } bool linked_list_traverse(linked_list* p_linked_list, traverse_func traverse_func) { linked_list_node* p_node; if (p_linked_list == NULL || traverse_func == NULL) { return false; } p_node = p_linked_list->p_head; while (p_node != NULL) { (*traverse_func)(p_node->p_data); p_node = p_node->p_next; } return true; } #endif // _LINKED_LIST_C_
code/data_structures/src/list/singly_linked_list/singly_linked_list.cpp
#include "singly_linked_list.h" int main() { Linkedlist<int> link; for (int i = 10; i > 0; --i) link.rearAdd(i); link.print(); std::cout << link.size() << std::endl; Linkedlist<int> link1(link); link1 = link1; link1.print(); link1.deletePos(100); link1.modify(5, 100); link1.insert(3, 50); std::cout << link1.size() << std::endl; link1.print(); link1.removeKthNodeFromEnd(3); std::cout<<"After deleting 3rd node from the end\n"; link1.print(); link1.sort(); link1.print(); link1.destroy(); std::cout << link1.size() << std::endl; return 0; }
code/data_structures/src/list/singly_linked_list/singly_linked_list.cs
namespace LinkedList { class Node<T> { // properties private T value; private Node<T> nextNode; // constructors public Node(T value, Node<T> nextNode) { this.value = value; this.nextNode = nextNode; } public Node(T value) { this.value = value; this.nextNode = null; } public Node() { this.value = default(T); this.nextNode = null; } // getters public T getValue() { return this.value; } public Node<T> getNextNode() { return nextNode; } // setters public void setValue(T value) { this.value = value; } public void setNextNode(Node<T> nextNode) { this.nextNode = nextNode; } // sets the current object to the next node // in the linked list public void setNext() { if(this.nextNode == null) throw new Exception("Trying to move to null node"); else { this.value = nextNode.value; this.nextNode = nextNode.nextNode; } } public override string ToString() { return value.ToString(); } } class LinkedList<T> { // properties private Node<T> head = null; // constructors public LinkedList() { // empty } // random access public T getValue(int index) { Node<T> node = head; for(int i = 0 ; i < index ; i++) { node.setNext(); } return node.getValue(); } // overriding the index operator public T this[int index] { get{return getValue(index);} } // the amount of items in the list public int count() { int counter = 0; Node<T> node = head; while(node.getNextNode() != null) { node.setNext(); counter++; } return counter; } // removes a node from the list public void remove(int index) { Node<T> node = head; for(int i = 0 ; i < index - 1 ; i++) { node.setNext(); } node.setNextNode(node.getNextNode().getNextNode()); } // ToString method public override string ToString() { string s = ""; Node<T> node = head; while(node != null || node.getNextNode() != null) { s += node.getValue().ToString() + '\n'; node.setNext(); } return s; } // returns the head node public Node<T> getHeadNode() { return head; } // add a value to the end public void append(T value) { Node<T> node = head; Node<T> newNode = new Node<T>(value); if(head == null) { head = newNode; } else { while(node.getNextNode() != null) node.setNext(); node.setNextNode(node); } } // insert a node in the middle public void insert(int index, T value) { Node<T> node = head; Node<T> newNode = new Node<T>(value); for(int i = 0 ; i < index - 1; i++) { node.setNext(); } newNode.setNextNode(node.getNextNode()); node.setNextNode(newNode); } } }
code/data_structures/src/list/singly_linked_list/singly_linked_list.go
package main import "fmt" type node struct { next *node label string } func (list *node) insert(new_label string) *node { if list == nil { new_node := &node { next: nil, label: new_label, } return new_node } else if list.next == nil { new_node := &node{ next: nil, label: new_label, } list.next = new_node } else { list.next.insert(new_label) } return nil } func (list *node) print_list() { head := list.next for head != nil { fmt.Println(head.label) head = head.next } } func (list *node) remove(remove_label string) { if list.next == nil { return } else if list.next.label == remove_label { list.next = list.next.next } else { list.next.remove(remove_label) } } func main() { l := &node{ next: nil, label: "-1", } l.insert("a") l.insert("b") l.insert("c") l.insert("d") l.insert("e") l.print_list() fmt.Println("After Removing label C") l.remove("c") l.print_list() }
code/data_structures/src/list/singly_linked_list/singly_linked_list.h
#pragma once #include <iostream> template <typename T> struct Node { T date; Node* pNext; }; template <typename T> class Linkedlist { public: Linkedlist(); Linkedlist(const Linkedlist<T> &list); Linkedlist<T>& operator= (const Linkedlist<T> &rhs); ~Linkedlist(); void headAdd(const T& date); void rearAdd(const T& date); int size() const; bool isEmpty() const; void print() const; T getPos(int pos) const; void insert(int pos, const T& data); void deletePos(int pos); void modify(int pos, const T& date); int find(const T& date); void sort(); void destroy(); void removeKthNodeFromEnd(int k); private: Node<T>* header; int length; }; template <typename T> Linkedlist<T>::Linkedlist() : header(nullptr), length(0) { }; template <typename T> Linkedlist<T>::Linkedlist(const Linkedlist<T> &list) : header(nullptr), length(0) { int i = 1; while (i <= list.size()) { rearAdd(list.getPos(i)); i++; } } template <typename T> Linkedlist<T>& Linkedlist<T>::operator= (const Linkedlist<T> &rhs) { if (this == &rhs) return *this; destroy(); for (int i = 1; i <= rhs.size(); ++i) rearAdd(rhs.getPos(i)); return *this; } template <typename T> Linkedlist<T>::~Linkedlist() { destroy(); } template <typename T> void Linkedlist<T>::headAdd(const T& date) { Node<T> *pNode = new Node<T>; pNode->date = date; pNode->pNext = nullptr; if (header == nullptr) header = pNode; else { pNode->pNext = header; header = pNode; } length++; } template <typename T> void Linkedlist<T>::rearAdd(const T& date) { Node<T> *pNode = new Node<T>; pNode->date = date; pNode->pNext = nullptr; if (header == nullptr) header = pNode; else { Node<T>* rear = header; while (rear->pNext != nullptr) rear = rear->pNext; rear->pNext = pNode; } length++; } template <typename T> int Linkedlist<T>::size() const { return length; } template <typename T> bool Linkedlist<T>::isEmpty() const { return header == nullptr; } template <typename T> void Linkedlist<T>::print() const { Node<T> *pTemp = header; int count = 0; while (pTemp != nullptr) { std::cout << pTemp->date << "\t"; pTemp = pTemp->pNext; count++; if (count % 5 == 0) std::cout << std::endl; } std::cout << std::endl; } template <typename T> T Linkedlist<T>::getPos(int pos) const { if (pos < 1 || pos > length) std::cerr << "get element position error!" << std::endl; else { int i = 1; Node<T> *pTemp = header; while (i++ < pos) pTemp = pTemp->pNext; return pTemp->date; } } template <typename T> void Linkedlist<T>::insert(int pos, const T& date) { if (pos < 1 || pos > length) std::cerr << "insert element position error!" << std::endl; else { if (pos == 1) { Node<T> *pTemp = new Node<T>; pTemp->date = date; pTemp->pNext = header; header = pTemp; } else { int i = 1; Node<T> *pTemp = header; while (++i < pos) pTemp = pTemp->pNext; Node<T> *pInsert = new Node<T>; pInsert->date = date; pInsert->pNext = pTemp->pNext; pTemp->pNext = pInsert; } length++; } return; } template <typename T> void Linkedlist<T>::deletePos(int pos) { if (pos < 0 || pos > length) std::cerr << "delete element position error!" << std::endl; else { Node<T> *deleteElement; if (pos == 0) { deleteElement = header; header = header->pNext; } else { int i = 0; Node<T> *pTemp = header; while (++i < pos) pTemp = pTemp->pNext; deleteElement = pTemp->pNext; pTemp->pNext = deleteElement->pNext; } delete deleteElement; length--; } return; } template <typename T> void Linkedlist<T>::modify(int pos, const T& date) { if (pos < 1 || pos > length) std::cerr << "modify element position error!" << std::endl; else { if (pos == 1) header->date = date; else { Node<T> *pTemp = header; int i = 1; while (i++ < pos) pTemp = pTemp->pNext; pTemp->date = date; } } return; } template <typename T> int Linkedlist<T>::find(const T& date) { int i = 1; int ret = -1; Node<T> *pTemp = header; while (!pTemp) { if (pTemp->date == date) { ret = i; break; } i++; pTemp = pTemp->pNext; } return ret; } template <typename T> void Linkedlist<T>::sort() { if (length > 1) { for (int i = length; i > 0; --i) for (int j = 1; j < i; j++) { T left = getPos(j); T right = getPos(j + 1); if (left > right) { modify(j, right); modify(j + 1, left); } } } return; } template <typename T> void Linkedlist<T>::destroy() { while (header != nullptr) { Node<T> *pTemp = header; header = header->pNext; delete pTemp; } length = 0; } template <typename T> void Linkedlist<T>::removeKthNodeFromEnd(int k) { if(k<=0) return; Node<T> *pTemp = header; while(pTemp!=nullptr && k--) pTemp = pTemp->pNext; if(k==0) { Node<T> *kthNode = header; header = header->pNext; delete kthNode; length =length - 1; return; } else if(pTemp==nullptr) return; Node<T> *kthNode = header; while(pTemp->pNext != nullptr) { pTemp = pTemp->pNext; kthNode = kthNode->pNext; } Node<T> *toBeDeleted = kthNode->pNext; kthNode->pNext = kthNode->pNext->pNext; delete toBeDeleted; length = length - 1; return; }
code/data_structures/src/list/singly_linked_list/singly_linked_list.java
/* Part of Cosmos by OpenGenus Foundation */ class SinglyLinkedList<T> { private Node head; public SinglyLinkedList() { head = null; } public void insertHead(T data) { Node<T> newNode = new Node<>(data); //Create a new link with a value attached to it newNode.next = head; //Set the new link to point to the current head head = newNode; //Now set the new link to be the head } public Node insertNth(T data, int position) { Node<T> newNode = new Node<>(data); if (position == 0) { newNode.next = head; return newNode; } Node current = head; while (--position > 0) { current = current.next; } newNode.next = current.next; current.next = newNode; return head; } public Node deleteHead() { Node temp = head; head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head return temp; } public void reverse(){ head = reverseList(head); } private Node reverseList(Node node){ if (node == null || node.next == null) return node; Node reversedHead = reverseList(node.next); node.next.next = node; node.next = null; return reversedHead; } public boolean isEmpty() { return (head == null); } public String toString() { String s = new String(); Node current = head; while (current != null) { s += current.getValue() + " -> "; current = current.next; } return s; } /** * Node is a private inner class because only the SinglyLinkedList class should have access to it */ private class Node<T> { /** The value of the node */ public T value; /** Point to the next node */ public Node next; //This is what the link will point to public Node(T value) { this.value = value; } public T getValue() { return value; } } public static void main(String args[]) { SinglyLinkedList<Integer> myList = new SinglyLinkedList<>(); System.out.println(myList.isEmpty()); //Will print true myList.insertHead(5); myList.insertHead(7); myList.insertHead(10); System.out.println(myList); // 10(head) --> 7 --> 5 myList.deleteHead(); System.out.println(myList); // 7(head) --> 5 } }
code/data_structures/src/list/singly_linked_list/singly_linked_list.js
/* Part of Cosmos by OpenGenus Foundation */ /* SinglyLinkedList!! * A linked list is implar to an array, it hold values. * However, links in a linked list do not have indexes. With * a linked list you do not need to predetermine it's size as * it grows and shrinks as it is edited. This is an example of * a singly linked list. */ //Functions - add, remove, indexOf, elementAt, addAt, removeAt, view //Creates a LinkedList function LinkedList() { //Length of linklist and head is null at start var length = 0; var head = null; //Creating Node with element's value var Node = function(element) { this.element = element; this.next = null; }; //Returns length this.size = function() { return length; }; //Returns the head this.head = function() { return head; }; //Creates a node and adds it to linklist this.add = function(element) { var node = new Node(element); //Check if its the first element if (head === null) { head = node; } else { var currentNode = head; //Loop till there is node present in the list while (currentNode.next) { currentNode = currentNode.next; } //Adding node to the end of the list currentNode.next = node; } //Increment the length length++; }; //Removes the node with the value as param this.remove = function(element) { var currentNode = head; var previousNode; //Check if the head node is the element to remove if (currentNode.element === element) { head = currentNode.next; } else { //Check which node is the node to remove while (currentNode.element !== element) { previousNode = currentNode; currentNode = currentNode.next; } //Removing the currentNode previousNode.next = currentNode.next; } //Decrementing the length length--; }; //Return if the list is empty this.isEmpty = function() { return length === 0; }; //Returns the index of the element passed as param otherwise -1 this.indexOf = function(element) { var currentNode = head; var index = -1; while (currentNode) { index++; //Checking if the node is the element we are searching for if (currentNode.element === element) { return index + 1; } currentNode = currentNode.next; } return -1; }; //Returns the element at an index this.elementAt = function(index) { var currentNode = head; var count = 0; while (count < index) { count++; currentNode = currentNode.next; } return currentNode.element; }; //Adds the element at specified index this.addAt = function(index, element) { index--; var node = new Node(element); var currentNode = head; var previousNode; var currentIndex = 0; //Check if index is out of bounds of list if (index > length) { return false; } //Check if index is the start of list if (index === 0) { node.next = currentNode; head = node; } else { while (currentIndex < index) { currentIndex++; previousNode = currentNode; currentNode = currentNode.next; } //Adding the node at specified index node.next = currentNode; previousNode.next = node; } //Incrementing the length length++; }; //Removes the node at specified index this.removeAt = function(index) { index--; var currentNode = head; var previousNode; var currentIndex = 0; //Check if index is present in list if (index < 0 || index >= length) { return null; } //Check if element is the first element if (index === 0) { head = currentNode.next; } else { while (currentIndex < index) { currentIndex++; previousNode = currentNode; currentNode = currentNode.next; } previousNode.next = currentNode.next; } //Decrementing the length length--; return currentNode.element; }; //Function to view the LinkedList this.view = function() { var currentNode = head; var count = 0; while (count < length) { count++; console.log(currentNode.element); currentNode = currentNode.next; } }; } //Implementation of LinkedList var linklist = new LinkedList(); linklist.add(2); linklist.add(5); linklist.add(8); linklist.add(12); linklist.add(17); console.log(linklist.size()); console.log(linklist.removeAt(4)); linklist.addAt(4, 15); console.log(linklist.indexOf(8)); console.log(linklist.size()); linklist.view();
code/data_structures/src/list/singly_linked_list/singly_linked_list.py
# Part of Cosmos by OpenGenus Foundation class Node: def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data def get_next(self): return self.next def set_next(self, new_next): self.next = new_next class LinkedList: def __init__(self): self.head = None def size(self): cur_node = self.head length = 0 while current_head != None: length += 1 cur_node = current_head.get_next() return length def search(self, data): cur_node = self.head while cur_node != None: if cur_node.get_data() == data: return cur_node else: cur_node = cur_node.get_next() return None def delete(self, data): cur_node = self.head prev_node = None while cur_node != None: if cur_node.get_data() == data: if cur_node == self.head: self.head = current.get_next() else: next_node = current.get_next() prev_node.set_next(next_node) return cur_node prev_node = cur_node cur_node = cur.get_next() return None def print_list(self): start = 1 cur_node = self.head while cur_node != None: if start == 1: start = 0 else: print("->"), print(cur_node.get_data()), cur_node = cur_node.get_next() def insert(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node
code/data_structures/src/list/singly_linked_list/singly_linked_list.rb
# Part of Cosmos by OpenGenus Foundation class Node attr_accessor :data attr_accessor :next def initialize(data) @data = data @next = nil end end class LinkedList attr_reader :size def initialize @head = nil @size = 0 end # Add a new node at end of linked list def add!(data) if @head.nil? @head = Node.new(data) else current_node = @head current_node = current_node.next until current_node.next.nil? current_node.next = Node.new(data) end @size += 1 nil end # Insert a new node at index def insert!(index, data) # If index is not in list yet, just assume add at end return add!(data) if index >= @size current_node = @head prev_node = nil current_index = 0 until current_node.nil? if index == current_index new_node = Node.new(data) new_node.next = current_node if current_node == @head @head = new_node else prev_node.next = new_node end end current_index += 1 prev_node = current_node current_node = current_node.next end @size += 1 nil end # Get node at index def get(index) current_index = 0 current_node = @head until current_node.nil? return current_node.data if index == current_index current_index += 1 current_node = current_node.next end nil end # Return node at index def remove!(index) current_index = 0 current_node = @head prev_node = nil until current_node.nil? if index == current_index if current_node == @head @head = current_node.next else prev_node.next = current_node.next end # We probably don't want to have the next node when returning the deleted node current_node.next = nil return current_node end current_index += 1 prev_node = current_node current_node = current_node.next end nil end # Return list as a string def to_s current_node = @head as_str = '' until current_node.nil? as_str << ' -> ' unless current_node == @head as_str << current_node.data.to_s current_node = current_node.next end as_str end end
code/data_structures/src/list/singly_linked_list/singly_linked_list.swift
// Part of Cosmos by OpenGenus Foundation import Foundation public struct Node<T> { private var data: T? private var next: [Node<T>?] = [] init() { self.data = nil } init(data: T) { self.data = data } func getData() -> T? { return self.data } func getNext() -> Node<T>? { return self.next[0] } mutating func setNext(next: Node<T>?) { self.next = [next] } } public struct LinkedList<T> { private var head: Node<T>? init() { self.head = nil } init(head: Node<T>?) { self.head = head } func size() -> Int { if var current_node = head { var len = 1 while let next = current_node.getNext() { current_node = next len += 1 } return len } return 0 } mutating func insert(data: T) { var node = Node<T>(data: data) node.setNext(next: self.head) self.head = node } }
code/data_structures/src/list/singly_linked_list/singly_linked_list_menu_driven.c
// use -1 option to exit // to learn about singly link list visit https://blog.bigoitsolution.com/learn/data-structures/922/ #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; int main() { int opt, value, flag, loc; struct Node *head, *new_node, *temp; head = (struct Node*)malloc(sizeof(struct Node)); head = NULL; // initially head is empty do { printf("Insertion : \n"); printf("1. At beginning\t\t2. In between\t\t3. At end\n"); printf("Deletion : \n"); printf("4. From beginning\t5. From between\t\t6. From end\n"); printf("Other :\n"); printf("7. Size\t\t\t8. Is Empty\t\t9. Search\n"); printf(" \t\t\t0. Print\n> "); scanf("%d", &opt); switch(opt) { // case to insert node in the begining case 1: printf("enter any integer "); scanf("%d", &value); new_node = (struct Node*)malloc(sizeof(struct Node)); if(new_node == NULL) { printf("Failed to allocate memory\n"); return 0; } new_node->data = value; new_node->next = NULL; if(head == NULL) { head = new_node; } else { new_node->next = head; head = new_node; } new_node = NULL; free(new_node); break; // case to add node at location case 2: if(head == NULL) { printf("List is empty\n"); break; } printf("enter an integer "); scanf("%d", &value); new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = value; new_node->next = NULL; printf("enter location "); scanf("%d", &loc); flag = 1; loc--; // because we hve to stop traversing before the location temp = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp->next!=NULL && flag!=loc) { temp=temp->next; flag++; } new_node->next = temp->next; temp->next = new_node; temp = NULL; new_node = NULL; free(temp); free(new_node); break; // case to add node at last case 3: printf("enter an integer "); scanf("%d", &value); new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->next = NULL; new_node->data = value; if(head == NULL) { head = new_node; } else { temp = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp->next != NULL) temp = temp->next; temp->next = new_node; } temp = NULL; free(temp); new_node = NULL; free(new_node); break; // case to delete node from begining case 4: if(head == NULL) { printf("List is empty\n"); } else { temp = (struct Node*)malloc(sizeof(struct Node)); temp = head; head = head->next; printf("%d is deleted\n", temp->data); free(temp); } break; // case to delete node from a location case 5: if(head==NULL) { printf("List is empty\n"); } else { printf("enter location "); scanf("%d", &loc); loc--; flag = 1; temp = (struct Node*)malloc(sizeof(struct Node)); new_node = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp->next!=NULL && flag!=loc) { temp=temp->next; flag++; } new_node = temp->next; printf("%d is deleted\n", new_node->data); temp->next = new_node->next; temp = NULL; free(new_node); free(temp); } break; // case to delete node from last case 6: if(head==NULL) { printf("List is empty\n"); } else { temp = (struct Node*)malloc(sizeof(struct Node)); new_node = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp->next->next!=NULL) { temp=temp->next; } new_node = temp->next; printf("%d is deleted", new_node->data); temp->next = NULL; free(new_node); temp = NULL; free(temp); } break; // case to print the size of list case 7: printf("Size is : "); if(head==NULL) { printf("0\n"); } else { flag = 0; temp = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp!=NULL) { flag++; temp=temp->next; } printf("%d\n", flag); free(temp); } break; // case to check whether the list is empty or not case 8: if(head==NULL) { printf("List is empty\n"); } else { printf("List is not empty\n"); } break; // case to print the location(s) of a node->data case 9: if(head == NULL) { printf("List is empty\n"); } else { flag = 1; printf("enter number to search "); scanf("%d", &value); printf("%d is found at : ", value); temp = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp!=NULL) { if(temp->data == value) printf("%d ", flag); flag++; temp = temp->next; } printf("\n"); free(temp); } break; // case to print the list case 0: if(head==NULL) { printf("List is empty\n"); } else { temp = (struct Node*)malloc(sizeof(struct Node)); temp = head; while(temp!=NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); free(temp); } break; } printf("\n=====================================\n"); }while(opt!=-1); free(head); return 0; }
code/data_structures/src/list/singly_linked_list/singly_linked_list_with_3_nodes.java
package linkedlist; public 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 static void main(String args[]) { LinkedList ll = new LinkedList(); ll.head = new Node(1); Node second = new Node(2); Node third = new Node(3); ll.head.next = second; second.next = third; ll.printList(); } }
code/data_structures/src/list/singly_linked_list/singly_linked_list_with_classes.cpp
#include <iostream> class Node { private: int _data; Node *_next; public: Node() { } void setData(int Data) { _data = Data; } void setNext(Node *Next) { if (Next == NULL) _next = NULL; else _next = Next; } int Data() { return _data; } Node *Next() { return _next; } }; class LinkedList { private: Node *head; public: LinkedList() { head = NULL; } void insert_back(int data); void insert_front(int data); void init_list(int data); void print_List(); }; void LinkedList::print_List() { Node *tmp = head; //Checking the list if there is a node or not. if (tmp == NULL) { std::cout << "List is empty\n"; return; } //Checking only one node situation. if (tmp->Next() == NULL) std::cout << "Starting: " << tmp->Data() << "Next Value > NULL\n"; else while (tmp != NULL) { std::cout << tmp->Data() << " > "; tmp = tmp->Next(); } } /*inserting a value infront of the */ void LinkedList::insert_back(int data) { //Creating a node Node *newNode = new Node(); newNode->setData(data); newNode->setNext(NULL); //Creating a temporary pointer. Node *tmp = head; if (tmp != NULL) { while (tmp->Next() != NULL) tmp = tmp->Next(); tmp->setNext(newNode); } else head = newNode; } /*Inserting a value in front of the head node.*/ void LinkedList::insert_front(int data) { // creating a new node. Node *newNode = new Node(); newNode->setData(data); newNode->setNext(NULL); newNode->setNext(head); head = newNode; } /*Initializing the list with a value.*/ void LinkedList::init_list(int data) { //creating a node Node *newNode = new Node(); newNode->setData(data); newNode->setNext(NULL); if (head != NULL) head = NULL; head = newNode; } int main() { //Creating a list LinkedList list; //Initilizing it with 5 list.init_list(5); list.insert_back(6); list.insert_front(4); list.print_List(); }
code/data_structures/src/list/skip_list/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/data_structures/src/list/skip_list/skip_list.c
#include <stdlib.h> #include <stdio.h> #include <limits.h> // Part of Cosmos by OpenGenus Foundation #define SKIPLIST_MAX_LEVEL 6 typedef struct snode { int key; int value; struct snode **forward; } snode; typedef struct skiplist { int level; int size; struct snode *header; } skiplist; skiplist *skiplist_init(skiplist *list) { int i; snode *header = (snode *) malloc(sizeof(struct snode)); list->header = header; header->key = INT_MAX; header->forward = (snode **) malloc( sizeof(snode*) * (SKIPLIST_MAX_LEVEL + 1)); for (i = 0; i <= SKIPLIST_MAX_LEVEL; i++) { header->forward[i] = list->header; } list->level = 1; list->size = 0; return list; } static int rand_level() { int level = 1; while (rand() < RAND_MAX / 2 && level < SKIPLIST_MAX_LEVEL) level++; return level; } int skiplist_insert(skiplist *list, int key, int value) { snode *update[SKIPLIST_MAX_LEVEL + 1]; snode *x = list->header; int i, level; for (i = list->level; i >= 1; i--) { while (x->forward[i]->key < key) x = x->forward[i]; update[i] = x; } x = x->forward[1]; if (key == x->key) { x->value = value; return 0; } else { level = rand_level(); if (level > list->level) { for (i = list->level + 1; i <= level; i++) { update[i] = list->header; } list->level = level; } x = (snode *) malloc(sizeof(snode)); x->key = key; x->value = value; x->forward = (snode **) malloc(sizeof(snode*) * (level + 1)); for (i = 1; i <= level; i++) { x->forward[i] = update[i]->forward[i]; update[i]->forward[i] = x; } } return 0; } snode *skiplist_search(skiplist *list, int key) { snode *x = list->header; int i; for (i = list->level; i >= 1; i--) { while (x->forward[i]->key < key) x = x->forward[i]; } if (x->forward[1]->key == key) { return x->forward[1]; } else { return NULL; } return NULL; } static void skiplist_node_free(snode *x) { if (x) { free(x->forward); free(x); } } int skiplist_delete(skiplist *list, int key) { int i; snode *update[SKIPLIST_MAX_LEVEL + 1]; snode *x = list->header; for (i = list->level; i >= 1; i--) { while (x->forward[i]->key < key) x = x->forward[i]; update[i] = x; } x = x->forward[1]; if (x->key == key) { for (i = 1; i <= list->level; i++) { if (update[i]->forward[i] != x) break; update[i]->forward[1] = x->forward[i]; } skiplist_node_free(x); while (list->level > 1 && list->header->forward[list->level] == list->header) list->level--; return 0; } return 1; } static void skiplist_dump(skiplist *list) { snode *x = list->header; while (x && x->forward[1] != list->header) { printf("%d[%d]->", x->forward[1]->key, x->forward[1]->value); x = x->forward[1]; } printf("NIL\n"); } int main() { int arr[] = { 3, 6, 9, 2, 11, 1, 4 }, i; skiplist list; skiplist_init(&list); printf("Insert:--------------------\n"); for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { skiplist_insert(&list, arr[i], arr[i]); } skiplist_dump(&list); printf("Search:--------------------\n"); int keys[] = { 3, 4, 7, 10, 111 }; for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) { snode *x = skiplist_search(&list, keys[i]); if (x) { printf("key = %d, value = %d\n", keys[i], x->value); } else { printf("key = %d, not fuound\n", keys[i]); } } printf("Search:--------------------\n"); skiplist_delete(&list, 3); skiplist_delete(&list, 9); skiplist_dump(&list); return 0; }
code/data_structures/src/list/skip_list/skip_list.cpp
/** * skip list C++ implementation * * Average Worst-case * Space O(n) O(n log n) * Search O(log n) 0(n) * Insert O(log n) 0(n) * Delete O(log n) 0(n) * Part of Cosmos by OpenGenus Foundation */ #include <algorithm> // std::less, std::max #include <cassert> // assert #include <iostream> // std::cout, std::endl, std::ostream #include <map> // std::map #include <stdlib.h> // rand, srand #include <time.h> // time template <typename val_t> class skip_list; template <typename val_t> std::ostream & operator<<(std::ostream &os, const skip_list<val_t> &jls); template <typename val_t> class skip_list { private: /** * skip_node */ struct skip_node { val_t data; skip_node **forward; int height; skip_node(int ht) : forward{new skip_node*[ht]}, height{ht} { for (int i = 0; i < ht; ++i) forward[i] = nullptr; } skip_node(const val_t &ele, int ht) : skip_node(ht) { data = ele; } ~skip_node() { if (forward[0]) delete forward[0]; delete[] forward; } }; /* member variables */ skip_node *head_; int size_, cur_height_; constexpr const static int MAX_HEIGHT = 10; constexpr const static float PROB = 0.5f; /* private functions */ bool coin_flip() { return ((float) rand() / RAND_MAX) < PROB; } int rand_height() { int height = 1; for (; height < MAX_HEIGHT && coin_flip(); ++height) { } return height; } skip_node ** find(const val_t &ele) { auto comp = std::less<val_t>(); skip_node **result = new skip_node*[cur_height_], *cur_node = head_; for (int lvl = cur_height_ - 1; lvl >= 0; --lvl) { while (cur_node->forward[lvl] && comp(cur_node->forward[lvl]->data, ele)) cur_node = cur_node->forward[lvl]; result[lvl] = cur_node; } return result; } void print(std::ostream &os) const { int i; for (skip_node *n = head_; n != nullptr; n = n->forward[0]) { os << n->data << ": "; for (i = 0; i < cur_height_; ++i) { if (i < n->height) os << "[ ] "; else os << " | "; } os << std::endl; os << " "; for (i = 0; i < cur_height_; ++i) os << " | "; os << std::endl; } } public: /* Default C'tor */ skip_list() : head_{new skip_node(MAX_HEIGHT)}, size_{0}, cur_height_{0} { srand((unsigned)time(0)); } /* D'tor */ ~skip_list() { delete head_; } /** * size * @return - the number of elements in the list */ int size() { return size_; } /** * insert * @param ele - the element to be inserted into the list */ void insert(const val_t &ele) { int new_ht = rand_height(); skip_node *new_node = new skip_node(ele, new_ht); cur_height_ = std::max(new_ht, cur_height_); skip_node **pre = find(ele); for (int i = 0; i < new_ht; ++i) { new_node->forward[i] = pre[i]->forward[i]; pre[i]->forward[i] = new_node; } ++size_; delete[] pre; } /** * contains * @param ele - the element to search for * @retrun - true if the element is in the list, false otherwise */ bool contains(const val_t &ele) { skip_node **pre = find(ele); bool result = pre[0] && pre[0]->forward[0] && pre[0]->forward[0]->data == ele; delete[] pre; return result; } /** * remove * @param ele - the element to delete if found */ void remove(const val_t &ele) { if (!contains(ele)) { std::cout << ele << " not found!" << std::endl; return; } skip_node *tmp, **pre = find(ele), *del = pre[0]->forward[0]; for (int i = 0; i < cur_height_; ++i) { tmp = pre[i]->forward[i]; if (tmp != nullptr && tmp->data == ele) { pre[i]->forward[i] = tmp->forward[i]; tmp->forward[i] = nullptr; } } --size_; delete del; delete[] pre; } friend std::ostream & operator<< <val_t>(std::ostream &os, const skip_list<val_t> &ls); }; // skip_node template<typename val_t> std::ostream & operator<<(std::ostream &os, const skip_list<val_t> &ls) { ls.print(os); return os; } int main() { auto ints = { 1, 4, 2, 7, 9, 3, 5, 8, 6 }; skip_list<int> isl; for (auto i : ints) { isl.insert(i); std::cout << isl << std::endl; } for (auto i : ints) { assert(isl.contains(i)); std::cout << "removing " << i << std::endl; isl.remove(i); std::cout << isl << std::endl; } return 0; }
code/data_structures/src/list/skip_list/skip_list.java
// Part of Cosmos by OpenGenus Foundation import java.util.*; public class SkipList<E> { /** Initialize the random variable */ static private Random value = new Random(); // Hold the Random class object /** Create a random number function from the standard Java Random class. Turn it into a uniformly distributed value within the range 0 to n-1 by taking the value mod n. @param n The upper bound for the range. @return A value in the range 0 to n-1. */ static int random(int n) { return Math.abs(value.nextInt()) % n; } // SkipNode class is a fairly passive data structure // that holds the key and value of a dictionary entry // and an array of pointers to help implement the skip list. private class SkipNode<E> { private int key; private E element; private SkipNode<E>[] forward; // make a skip node with data, but don't wire it in yet public SkipNode( int key, E element, int levels ) { this.key = key; this.element = element; this.forward = (SkipNode<E>[]) new SkipNode[levels+1]; for (int i = 0; i <= levels; i++) this.forward[i] = null; } // make a skip node without data (designed for head node) public SkipNode( int levels ) { this.key = 0; this.element = null; this.forward = new SkipNode[levels+1]; for (int i = 0; i <= levels; i++) this.forward[i] = null; } // adjust this node to have newLevel forward pointers. // assumes newLevel >= this.forward.length public void adjustLevel( int newLevel ) { SkipNode[] oldf = this.forward; this.forward = new SkipNode[newLevel+1]; for (int i = 0; i < oldf.length; i++) this.forward[i] = oldf[i]; for (int i = oldf.length; i <= newLevel; i++) this.forward[i] = null; // there aren't any nodes this tall yet, so there is nothing to point to } // Print the contents of the forward vector (I.e. write out who // each level is pointing to). public void printForward( ) { for (int i = this.forward.length-1; i >= 0; i--) { if (this.forward[i] == null) System.out.println( "level : " + i + " ----> null" ); else System.out.println( "level : " + i + " ----> (" + this.forward[i].key() + " : " + this.forward[i].element() + ")"); } } // accessors public int key() { return this.key; } public E element() { return this.element; } } // Fields! private SkipNode head; // first node private int level; // max number of levels in the list private int size; // number of data elements in list public SkipList() { // it will start life as a humble linked list. this.level = 1; // make the head. It will contain no data this.head = new SkipNode( this.level ); this.size = 0; } /** Pick a level using a geometric distribution */ int randomLevel() { //return 1; int lev; for (lev=0; random(2) == 0; lev++); // Do nothing return lev; } // adjust the head to have an array of newLevel levesl public void adjustHead(int newLevel) { this.head.adjustLevel( newLevel ); } /** Insert a record into the skiplist */ public void insert(int k, E newValue) { int newLevel = randomLevel(); // New node’s level if (newLevel > level) // If new node is deeper adjustHead(newLevel); // adjust the header this.level = newLevel; // and record new distance. // Track end of level SkipNode<E>[] update = (SkipNode<E>[]) new SkipNode[level+1]; SkipNode<E> x = this.head; // Start at header node for (int i=level; i>=0; i--) { // Find insert position while((x.forward[i] != null) && (k > x.forward[i].key())) x = x.forward[i]; update[i] = x; // Track end at level i } x = new SkipNode<E>(k, newValue, newLevel); for (int i=0; i <= newLevel; i++) { // Splice into list x.forward[i] = update[i].forward[i]; // Who x points to update[i].forward[i] = x; // Who y points to } this.size++; // Increment dictionary size } /** Skiplist Search */ public E find(int searchKey) { SkipNode<E> x = this.head; // Dummy header node for (int i=level; i>=0; i--) // For each level... while ((x.forward[i] != null) && // go forward (searchKey > x.forward[i].key())) x = x.forward[i]; // Go one last step x = x.forward[0]; // Move to actual record, if it exists if ((x != null) && (searchKey == x.key())) return x.element(); // Got it else return null; // Its not there } public void printContents() { SkipNode ptr = this.head; while (true) { if (ptr.forward[0] == null) break; ptr = ptr.forward[0]; System.out.println( ptr.key() + " : " + ptr.element() ); } } public void printEverything() { SkipNode ptr = this.head; System.out.println( "Head Node " ); ptr.printForward(); ptr = ptr.forward[0]; while (ptr != null) { System.out.println( "Node (" + ptr.key() + " : " + ptr.element() + ")" ); ptr.printForward(); ptr = ptr.forward[0]; } } public static void main( String[] args ) { SkipList<String> sl = new SkipList<String>(); sl.insert( 1, "One" ); System.out.println( "\nPrinting the list "); //System.out.println( "Printing the header array: "); //sl.head.printForward(); sl.printEverything(); sl.insert( 4, "Four" ); sl.insert( 10, "Ten" ); sl.insert( 3, "Three" ); sl.insert( 11, "Eleven" ); System.out.println( "\nPrinting the list "); sl.printEverything(); System.out.println( "\nPrinting just the traversal" ); sl.printContents(); } }
code/data_structures/src/list/skip_list/skip_list.rb
class Node attr_accessor :key attr_accessor :value attr_accessor :forward def initialize(k, v = nil) @key = k @value = v.nil? ? k : v @forward = [] end end class SkipList attr_accessor :level attr_accessor :header def initialize @header = Node.new(1) @level = 0 @max_level = 3 @p = 0.5 @node_nil = Node.new(1000000) @header.forward[0] = @node_nil end def search(search_key) x = @header @level.downto(0) do |i| while x.forward[i].key < search_key do x = x.forward[i] end end x = x.forward[0] if x.key == search_key return x.value else return nil end end def random_level v = 0 while rand < @p && v < @max_level v += 1 end v end def insert(search_key, new_value = nil) new_value = search_key if new_value.nil? update = [] x = @header @level.downto(0) do |i| while x.forward[i].key < search_key do x = x.forward[i] end update[i] = x end x = x.forward[0] if x.key == search_key x.value = new_value else v = random_level if v > @level (@level + 1).upto(v) do |i| update[i] = @header @header.forward[i] = @node_nil end @level = v end x = Node.new(search_key, new_value) 0.upto(v) do |i| x.forward[i] = update[i].forward[i] update[i].forward[i] = x end end end end
code/data_structures/src/list/skip_list/skip_list.scala
import java.util.Random import scala.collection.Searching._ import scala.reflect.ClassTag object SkipList { val MAX_LEVELS = 32; val random = new Random() } class SkipList[T](private var nextLists: Array[SkipList[T]], private var data: T) { def this(firstElement: T) = this(Array.ofDim(SkipList.MAX_LEVELS), firstElement) private def randomNumberOfLevels(maxLevels: Int): Int = { var i = SkipList.random.nextInt() var count = 1 while ((i & 1) == 1 && count < maxLevels) { count += 1 i = i >> 1 } count } def contains(target: T)(implicit ord: Ordering[T]): Boolean = { return contains(target, nextLists.length - 1) } def contains(target: T, level: Int)(implicit ord: Ordering[T]): Boolean = { // println(s"contains: level ${level}, target ${target}") if (level == 0) { return ( if (target == data) { true } else if (ord.lt(target, data)) { false } else if (nextLists(0) != null) { nextLists(0).contains(target, level) } else { false }) } else if (nextLists(level) == null || ord.lt(target, nextLists(level).data)) { return contains(target, level - 1) } else if (ord.gteq(target, nextLists(level).data)) { return nextLists(0).contains(target, level) } throw new RuntimeException("Shouldn't get here.") } def insert(newElement: T)(implicit ord: Ordering[T]): Unit = { insert(newElement, nextLists.length - 1, this) } def insert(newElement: T, level: Int, headOfList: SkipList[T])(implicit ord: Ordering[T]): Unit = { // println(s"insert: level ${level}, newElement ${newElement}, current element: ${data}.") if (level == 0) { if (newElement == data) { return } else if (nextLists(0) != null && ord.gteq(newElement, nextLists(0).data)) { return insert(newElement, level, headOfList) } else { // Create next node with random height and elements that don't fit into this node val numLevelsForNewNode = randomNumberOfLevels(SkipList.MAX_LEVELS) val nextNode = new SkipList(Array.ofDim[SkipList[T]](numLevelsForNewNode), newElement) // Fix bottom links, this -> new -> next nextNode.nextLists(0) = nextLists(0) nextLists(0) = nextNode if (ord.gt(data, newElement)) { nextNode.data = data data = newElement } return headOfList.insertNewNode(nextNode, nextNode.nextLists.length - 1) } } else if (nextLists(level) == null) { return insert(newElement, level - 1, headOfList) } else if (ord.gteq(newElement, nextLists(level).data)) { return nextLists(level).insert(newElement, level, headOfList) } throw new RuntimeException("Shouldn't get here.") } def insertNewNode(newNode: SkipList[T], startLevel: Int)(implicit ord: Ordering[T]): Unit = { var currentNode = this for (level <- startLevel until 0 by -1) { while (currentNode.nextLists(level) != null && ord.gteq(newNode.data, currentNode.nextLists(level).data)) { currentNode = currentNode.nextLists(level) } newNode.nextLists(level) = currentNode.nextLists(level) currentNode.nextLists(level) = newNode } } override def toString(): String = { data + (if (nextLists(0) == null) "" else ", " + nextLists(0)) } } object Main { def main(args: Array[String]): Unit = { val list = new SkipList(Array.ofDim[SkipList[String]](5), "aab") println(list) println(list.contains("aaa")) println(list.contains("aab")) list.insert("aaa") println(list) println(list.contains("aaa")) println(list.contains("aab")) list.insert("aac") println(list) println(list.contains("aaa")) println(list.contains("aab")) println(list.contains("aac")) } }
code/data_structures/src/list/skip_list/skip_list.swift
import Foundation public struct Stack<T> { fileprivate var array: [T] = [] public var isEmpty: Bool { return array.isEmpty } public var count: Int { return array.count } public mutating func push(_ element: T) { array.append(element) } public mutating func pop() -> T? { return array.popLast() } public func peek() -> T? { return array.last } } extension Stack: Sequence { public func makeIterator() -> AnyIterator<T> { var curr = self return AnyIterator { curr.pop() } } } private func coinFlip() -> Bool { return arc4random_uniform(2) == 1 } public class DataNode<Key: Comparable, Payload> { public typealias Node = DataNode<Key, Payload> var data: Payload? fileprivate var key: Key? var next: Node? var down: Node? public init(key: Key, data: Payload) { self.key = key self.data = data } public init(asHead head: Bool) {} } open class SkipList<Key: Comparable, Payload> { public typealias Node = DataNode<Key, Payload> fileprivate(set) var head: Node? public init() {} } extension SkipList { func findNode(key: Key) -> Node? { var currentNode: Node? = head var isFound: Bool = false while !isFound { if let node = currentNode { switch node.next { case .none: currentNode = node.down case .some(let value) where value.key != nil: if value.key == key { isFound = true break } else { if key < value.key! { currentNode = node.down } else { currentNode = node.next } } default: continue } } else { break } } if isFound { return currentNode } else { return nil } } func search(key: Key) -> Payload? { guard let node = findNode(key: key) else { return nil } return node.next!.data } } extension SkipList { private func bootstrapBaseLayer(key: Key, data: Payload) { head = Node(asHead: true) var node = Node(key: key, data: data) head!.next = node var currentTopNode = node while coinFlip() { let newHead = Node(asHead: true) node = Node(key: key, data: data) node.down = currentTopNode newHead.next = node newHead.down = head head = newHead currentTopNode = node } } private func insertItem(key: Key, data: Payload) { var stack = Stack<Node>() var currentNode: Node? = head while currentNode != nil { if let nextNode = currentNode!.next { if nextNode.key! > key { stack.push(currentNode!) currentNode = currentNode!.down } else { currentNode = nextNode } } else { stack.push(currentNode!) currentNode = currentNode!.down } } let itemAtLayer = stack.pop() var node = Node(key: key, data: data) node.next = itemAtLayer!.next itemAtLayer!.next = node var currentTopNode = node while coinFlip() { if stack.isEmpty { let newHead = Node(asHead: true) node = Node(key: key, data: data) node.down = currentTopNode newHead.next = node newHead.down = head head = newHead currentTopNode = node } else { let nextNode = stack.pop() node = Node(key: key, data: data) node.down = currentTopNode node.next = nextNode!.next nextNode!.next = node currentTopNode = node } } } func insert(key: Key, data: Payload) { if head != nil { if let node = findNode(key: key) { var currentNode = node.next while currentNode != nil && currentNode!.key == key { currentNode!.data = data currentNode = currentNode!.down } } else { insertItem(key: key, data: data) } } else { bootstrapBaseLayer(key: key, data: data) } } } extension SkipList { public func remove(key: Key) { guard let item = findNode(key: key) else { return } var currentNode = Optional(item) while currentNode != nil { let node = currentNode!.next if node!.key != key { currentNode = node continue } let nextNode = node!.next currentNode!.next = nextNode currentNode = currentNode!.down } } } extension SkipList { public func get(key: Key) -> Payload? { return search(key: key) } }
code/data_structures/src/list/stack_using_linked_list/stack_using_linked_list.c
#include<stdio.h> struct node { int data; struct node *next; }; struct node * head=0; //inserting an element void push(int x) { struct node * temp=0; temp=(struct node *)malloc(sizeof(struct node)); if(temp==0) { printf("\nOverflow"); return; } temp->data=x; temp->next=head; head=temp; } //delete an element void pop() { if(head==0) { printf("\nUnderflow"); return; } struct node * temp; temp=head; head=head->next; free(temp); } //printing the elements void print() { if(head==0) { printf("\nUnderflow"); return; } struct node *temp = head; printf("\n"); while(temp!=0) { printf("%d ",temp->data); temp=temp->next; } } int main() { print(); push(10); print(); push(20); push(30); print(); pop(); pop(); pop(); print(); pop(); return 0; }
code/data_structures/src/list/xor_linked_list/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/data_structures/src/list/xor_linked_list/xor_linked_list.cpp
/* * Part of Cosmos by OpenGenus Foundation * * xor linked list synopsis * *** incomplete *** *** ***Begin *** Iterator invalidation rules are NOT applicable. *** ***[x] Insertion: all iterators and references unaffected. ***[x] Erasure: only the iterators and references to the erased element is invalidated. ***[o] Resizing: as per insert/erase. *** ***Refer to: https://stackoverflow.com/questions/6438086/iterator-invalidation-rules ***End *** Iterator invalidation rules are NOT applicable. *** */ #ifndef XOR_LINKED_LIST_CPP #define XOR_LINKED_LIST_CPP #include <iterator> #include <algorithm> #include <exception> #include <cstddef> template<typename _Type> class XorLinkedList; template<class _Type> class ListIter; template<class _Type> class ListConstIter; template<typename _Type> class __Node { private: using value_type = _Type; using SPNode = __Node<value_type> *; public: explicit __Node(value_type value) : value_(value), around_(nullptr) { } inline value_type &value() { return value_; } inline const value_type &value() const { return value_; } inline void value(value_type v) { value_ = v; } private: value_type value_; void *around_; inline SPNode around(const SPNode &around) { return reinterpret_cast<SPNode>(reinterpret_cast<uintptr_t>(around) ^ reinterpret_cast<uintptr_t>(around_)); } inline void around(const SPNode &prev, const SPNode &next) { around_ = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(prev) ^ reinterpret_cast<uintptr_t>(next)); } friend XorLinkedList<value_type>; friend ListIter<value_type>; friend ListConstIter<value_type>; }; template<class _Type> class ListIter : public std::iterator<std::bidirectional_iterator_tag, _Type> { public: using value_type = _Type; using difference_type = std::ptrdiff_t; using pointer = _Type *; using reference = _Type &; using iterator_category = std::bidirectional_iterator_tag; private: using NodePtr = __Node<value_type> *; using Self = ListIter<value_type>; public: ListIter() { } explicit ListIter(NodePtr prev, NodePtr curr) : prev_(prev), curr_(curr) { } ListIter(const Self &it) : prev_(it.prev_), curr_(it.curr_) { } reference operator*() { return curr_->value(); } pointer operator->() { return &curr_->value(); } Self &operator++() { auto next = curr_->around(prev_); prev_ = curr_; curr_ = next; return *this; } Self operator++(int) { auto temp = *this; ++*this; return temp; } Self &operator--() { auto prevOfprev = prev_->around(curr_); curr_ = prev_; prev_ = prevOfprev; return *this; } Self operator--(int) { auto temp = *this; --*this; return temp; } bool operator==(const Self &other) const { return curr_ == other.curr_; } bool operator!=(const Self &other) const { return !(*this == other); } private: NodePtr prev_, curr_; friend XorLinkedList<value_type>; friend ListConstIter<value_type>; }; template<class _Type> class ListConstIter : public std::iterator<std::bidirectional_iterator_tag, _Type> { public: using value_type = _Type; using difference_type = std::ptrdiff_t; using pointer = const _Type *; using reference = const _Type &; using iterator_category = std::bidirectional_iterator_tag; private: using NodePtr = __Node<value_type> *; using Self = ListConstIter<value_type>; using Iter = ListIter<value_type>; public: ListConstIter() { } explicit ListConstIter(NodePtr prev, NodePtr curr) : prev_(prev), curr_(curr) { } ListConstIter(const Iter &it) : prev_(it.prev_), curr_(it.curr_) { } reference operator*() const { return curr_->value(); } pointer operator->() const { return &curr_->value(); } Self &operator++() { auto next = curr_->around(prev_); prev_ = curr_; curr_ = next; return *this; } Self operator++(int) { auto temp = *this; ++*this; return temp; } Self &operator--() { auto prevOfprev = prev_->around(curr_); curr_ = prev_; prev_ = prevOfprev; return *this; } Self operator--(int) { auto temp = *this; --*this; return temp; } bool operator==(const Self &other) const { return curr_ == other.curr_; } bool operator!=(const Self &other) const { return !(*this == other); } private: NodePtr prev_, curr_; Iter constCast() { return Iter(prev_, curr_); } friend XorLinkedList<value_type>; }; template<typename _Type> class XorLinkedList { private: using Node = __Node<_Type>; using NodePtr = __Node<_Type> *; using Self = XorLinkedList<_Type>; public: using value_type = _Type; using size_type = size_t; using difference_type = std::ptrdiff_t; using pointer = const value_type *; using const_pointer = const value_type *; using reference = value_type &; using const_reference = const value_type &; using iterator = ListIter<value_type>; using const_iterator = ListConstIter<value_type>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; explicit XorLinkedList() : sz_(0) { construct(); } XorLinkedList(const Self &list) : sz_(0) { construct(); std::for_each(list.begin(), list.end(), [&](value_type v) { push_back(v); }); }; XorLinkedList(std::initializer_list<value_type> &&vs) : sz_(0) { construct(); std::for_each(vs.begin(), vs.end(), [&](value_type v) { push_back(v); }); } ~XorLinkedList() { clear(); destruct(); } // element access inline reference back(); inline const_reference back() const; inline reference front(); inline const_reference front() const; // modifiers void clear(); template<class ... Args> reference emplace_back(Args&& ... args); template<class ... Args> reference emplace_front(Args&& ... args); iterator erase(const_iterator pos); iterator erase(const_iterator begin, const_iterator end); iterator insert(const_iterator pos, const value_type &v); iterator insert(const_iterator pos, size_type size, const value_type &v); iterator insert(const_iterator pos, value_type &&v); iterator insert(const_iterator pos, std::initializer_list<value_type> il); template<typename _InputIt> iterator insert(const_iterator pos, _InputIt first, _InputIt last); void pop_back(); void pop_front(); void push_back(const value_type &v); void push_front(const value_type &v); void resize(size_type count); void resize(size_type count, const value_type&value); void swap(Self&other); // capacity inline bool empty() const; inline size_type max_size() const; inline size_type size() const; // iterators iterator begin(); const_iterator begin() const; const_iterator cbegin() const; iterator end(); const_iterator end() const; const_iterator cend() const; reverse_iterator rbegin(); const_reverse_iterator rbegin() const; const_reverse_iterator crbegin() const; reverse_iterator rend(); const_reverse_iterator rend() const; const_reverse_iterator crend() const; // operations void merge(Self&other); void merge(Self&&other); template<class Compare> void merge(Self&other, Compare comp); template<class Compare> void merge(Self&&other, Compare comp); void reverse(); void sort(); template<class Compare> void sort(Compare comp); void splice(const_iterator pos, Self&other); void splice(const_iterator pos, Self&&other); void splice(const_iterator pos, Self&other, const_iterator it); void splice(const_iterator pos, Self&&other, const_iterator it); void splice(const_iterator pos, Self&other, const_iterator first, const_iterator last); void splice(const_iterator pos, Self&&other, const_iterator first, const_iterator last); void unique(); template<class BinaryPredicate> void unique(BinaryPredicate p); private: NodePtr prevOfBegin_, end_, nextOfEnd_; size_type sz_; inline void construct(); inline void destruct(); inline iterator insertImpl(const_iterator pos, const value_type &v); inline iterator eraseImpl(const_iterator pos); }; // element access template<typename _Type> inline auto XorLinkedList<_Type>::back()->reference { if (empty()) throw std::out_of_range("access to empty list !"); return end_->around(nextOfEnd_)->value(); } template<typename _Type> inline auto XorLinkedList<_Type>::back() const->const_reference { return const_cast<Self *>(this)->back(); } template<typename _Type> inline auto XorLinkedList<_Type>::front()->reference { if (empty()) throw std::out_of_range("access to empty list !"); return prevOfBegin_->around(nextOfEnd_)->value(); } template<typename _Type> inline auto XorLinkedList<_Type>::front() const->const_reference { return const_cast<Self *>(this)->front(); } // modifiers template<typename _Type> inline void XorLinkedList<_Type>::clear() { NodePtr begin = prevOfBegin_, nextOfBegin; begin = begin->around(nextOfEnd_); while (begin != end_) { nextOfBegin = begin->around(prevOfBegin_); prevOfBegin_->around(nextOfEnd_, nextOfBegin); nextOfBegin->around(prevOfBegin_, nextOfBegin->around(begin)); delete begin; begin = nextOfBegin; } sz_ = 0; } template<typename _Type> template<class ... Args> auto XorLinkedList<_Type>::emplace_back(Args&& ... args)->reference { } template<typename _Type> template<class ... Args> auto XorLinkedList<_Type>::emplace_front(Args&& ... args)->reference { } template<typename _Type> inline auto XorLinkedList<_Type>::erase(const_iterator pos)->iterator { return eraseImpl(pos); } template<typename _Type> inline auto XorLinkedList<_Type>::erase(const_iterator first, const_iterator last)->iterator { auto diff = std::distance(first, last); if (diff == 0) return first.constCast(); // check what is std return auto firstAfterEraseIter = first; while (diff--) firstAfterEraseIter = eraseImpl(firstAfterEraseIter); return firstAfterEraseIter.constCast(); } template<typename _Type> inline auto XorLinkedList<_Type>::insert(const_iterator pos, const value_type &v)->iterator { return insertImpl(pos, v); } template<typename _Type> inline auto XorLinkedList<_Type>::insert(const_iterator pos, size_type size, const value_type &v) ->iterator { if (size == 0) return pos.constCast(); auto curr = insert(pos, v); auto firstOfInsert = curr; ++curr; while (--size) curr = ++insert(curr, v); return firstOfInsert; } template<typename _Type> inline auto XorLinkedList<_Type>::insert(const_iterator pos, value_type &&v)->iterator { return insertImpl(pos, v); } template<typename _Type> inline auto XorLinkedList<_Type>::insert(const_iterator pos, std::initializer_list<value_type> il) ->iterator { if (il.begin() == il.end()) return pos.constCast(); auto curr = insert(pos, *il.begin()); auto firstOfInsert = curr; ++curr; auto begin = il.begin(); ++begin; std::for_each(begin, il.end(), [&](value_type v) { curr = ++insert(curr, v); }); return firstOfInsert; } template<typename _Type> template<typename _InputIt> inline auto XorLinkedList<_Type>::insert(const_iterator pos, _InputIt first, _InputIt last) ->iterator { if (first < last) { auto curr = insert(pos, *first); auto firstOfInsert = curr; ++curr; auto begin = first; ++begin; std::for_each(begin, last, [&](value_type it) { curr = ++insert(curr, it); }); return firstOfInsert; } return pos.constCast(); } template<typename _Type> void XorLinkedList<_Type>::pop_back() { // Calling pop_back on an empty container is undefined. erase(--end()); } template<typename _Type> void XorLinkedList<_Type>::pop_front() { // Calling pop_front on an empty container is undefined. erase(begin()); } template<typename _Type> void XorLinkedList<_Type>::push_back(const value_type &v) { insert(end(), v); } template<typename _Type> void XorLinkedList<_Type>::push_front(const value_type &v) { insert(begin(), v); } template<typename _Type> void XorLinkedList<_Type>::resize(size_type count) { } template<typename _Type> void XorLinkedList<_Type>::resize(size_type count, const value_type&value) { } template<typename _Type> void XorLinkedList<_Type>::swap(Self&other) { } // capacity template<typename _Type> inline bool XorLinkedList<_Type>::empty() const { return prevOfBegin_->around(nextOfEnd_) == end_; } template<typename _Type> inline auto XorLinkedList<_Type>::max_size() const->size_type { return static_cast<size_type>(-1) / sizeof(value_type); } template<typename _Type> inline auto XorLinkedList<_Type>::size() const->size_type { return sz_; } // iterators template<typename _Type> inline auto XorLinkedList<_Type>::begin()->iterator { return iterator(prevOfBegin_, prevOfBegin_->around(nextOfEnd_)); } template<typename _Type> auto XorLinkedList<_Type>::begin() const->const_iterator { return const_iterator(prevOfBegin_, prevOfBegin_->around(nextOfEnd_)); } template<typename _Type> auto XorLinkedList<_Type>::cbegin() const->const_iterator { return const_iterator(prevOfBegin_, prevOfBegin_->around(nextOfEnd_)); } template<typename _Type> inline auto XorLinkedList<_Type>::end()->iterator { return iterator(end_->around(nextOfEnd_), end_); } template<typename _Type> auto XorLinkedList<_Type>::end() const->const_iterator { return const_iterator(end_->around(nextOfEnd_), end_); } template<typename _Type> auto XorLinkedList<_Type>::cend() const->const_iterator { return const_iterator(end_->around(nextOfEnd_), end_); } template<typename _Type> inline auto XorLinkedList<_Type>::rbegin()->reverse_iterator { return reverse_iterator(end()); } template<typename _Type> auto XorLinkedList<_Type>::rbegin() const->const_reverse_iterator { return const_reverse_iterator(end()); } template<typename _Type> auto XorLinkedList<_Type>::crbegin() const->const_reverse_iterator { return const_reverse_iterator(cend()); } template<typename _Type> inline auto XorLinkedList<_Type>::rend()->reverse_iterator { return reverse_iterator(begin()); } template<typename _Type> auto XorLinkedList<_Type>::rend() const->const_reverse_iterator { return const_reverse_iterator(begin()); } template<typename _Type> auto XorLinkedList<_Type>::crend() const->const_reverse_iterator { return const_reverse_iterator(cbegin()); } // operations template<typename _Type> inline void XorLinkedList<_Type>::merge(Self&other) { } template<typename _Type> inline void XorLinkedList<_Type>::merge(Self&&other) { } template<typename _Type> template<class Compare> inline void XorLinkedList<_Type>::merge(Self&other, Compare comp) { } template<typename _Type> template<class Compare> inline void XorLinkedList<_Type>::merge(Self&&other, Compare comp) { } template<typename _Type> inline void XorLinkedList<_Type>::reverse() { std::swap(prevOfBegin_, end_); } template<typename _Type> inline void XorLinkedList<_Type>::sort() { } template<typename _Type> template<class Compare> inline void XorLinkedList<_Type>::sort(Compare comp) { } template<typename _Type> inline void XorLinkedList<_Type>::splice(const_iterator pos, Self&other) { } template<typename _Type> inline void XorLinkedList<_Type>::splice(const_iterator pos, Self&&other) { } template<typename _Type> inline void XorLinkedList<_Type>::splice(const_iterator pos, Self&other, const_iterator it) { } template<typename _Type> inline void XorLinkedList<_Type>::splice(const_iterator pos, Self&&other, const_iterator it) { } template<typename _Type> inline void XorLinkedList<_Type>::splice(const_iterator pos, Self&other, const_iterator first, const_iterator last) { } template<typename _Type> inline void XorLinkedList<_Type>::splice(const_iterator pos, Self&&other, const_iterator first, const_iterator last) { } template<typename _Type> inline void XorLinkedList<_Type>::unique() { } template<typename _Type> template<class BinaryPredicate> inline void XorLinkedList<_Type>::unique(BinaryPredicate p) { } // private functions template<typename _Type> inline void XorLinkedList<_Type>::construct() { end_ = new Node(0); prevOfBegin_ = new Node(0); nextOfEnd_ = new Node(0); end_->around(prevOfBegin_, nextOfEnd_); prevOfBegin_->around(nextOfEnd_, end_); nextOfEnd_->around(end_, prevOfBegin_); } template<typename _Type> inline void XorLinkedList<_Type>::destruct() { delete prevOfBegin_; delete end_; delete nextOfEnd_; } template<typename _Type> inline auto XorLinkedList<_Type>::insertImpl(const_iterator pos, const value_type &v) ->iterator { auto curr = pos.curr_; auto prev = pos.prev_; auto nextOfNext = curr->around(prev); auto prevOfPrev = prev->around(curr); auto newCurr = new Node(v); newCurr->around(prev, curr); curr->around(newCurr, nextOfNext); prev->around(prevOfPrev, newCurr); ++sz_; return iterator(prev, prev->around(prevOfPrev)); } template<typename _Type> auto XorLinkedList<_Type>::eraseImpl(const_iterator pos)->iterator { auto curr = pos.curr_; auto prev = pos.prev_; auto nextOfCurr = curr->around(prev); auto nextOfNext = nextOfCurr->around(curr); auto prevOfPrev = prev->around(curr); nextOfCurr->around(prev, nextOfNext); prev->around(prevOfPrev, nextOfCurr); delete curr; --sz_; return iterator(prev, nextOfCurr); } #endif // XOR_LINKED_LIST_CPP
code/data_structures/src/maxHeap/maxHeap.cpp
#include "maxHeap.h" using namespace std; void maxHeap::heapifyAdd(int idx) { int root = (idx-1)/2; if(heap[idx]>heap[root]) { int temp = heap[root]; heap[root] = heap[idx]; heap[idx] = temp; heapifyAdd(root); } } void maxHeap::heapifyRemove(int idx) { int max = idx; int leftIdx = idx*2+1; int rightIdx = idx*2+2; if(leftIdx<currSize&& heap[leftIdx]>heap[idx]) { max=leftIdx; } if(rightIdx<currSize&& heap[rightIdx]>heap[max]) { max=rightIdx; } if(max!=idx) // swap { int temp = heap[max]; heap[max] = heap[idx]; heap[idx] = temp; heapifyRemove(max); } } maxHeap::maxHeap(int capacity) { heap = new int[capacity] ; currSize = 0; this->capacity = capacity; } void maxHeap::insert(int itm) { if(currSize==capacity) return; heap[currSize] = itm; currSize++; heapifyAdd(currSize-1); } void maxHeap::remove() { if (currSize==0) return; heap[0] = heap[currSize-1]; currSize--; heapifyRemove(0); } void maxHeap::print() { for(int i =0; i<currSize;i++) { cout<< heap[i]; } cout<<endl; }
code/data_structures/src/maxHeap/maxHeap.h
#ifndef COSMOS_MAXHEAP_H #define COSMOS_MAXHEAP_H #include <iostream> class maxHeap { private : int* heap; int capacity; int currSize; void heapifyAdd(int idx); void heapifyRemove(int idx); public: maxHeap(int capacity); void insert(int itm); void remove(); void print(); }; #endif //COSMOS_MAXHEAP_H
code/data_structures/src/maxHeap/maxHeap.java
public class MaxHeap { private int[] heap; private int currSize; private int capacity; public MaxHeap(int capacity) { this.heap = new int[capacity]; this.currSize = 0; this.capacity = capacity; } private void heapifyAdd(int idx) { int root = (idx - 1) / 2; if(heap[idx] > heap[root]) { int temp = heap[root]; heap[root] = heap[idx]; heap[idx] = temp; heapifyAdd(root); } } private void heapifyRemove(int idx) { int max = idx; int leftIdx = idx * 2 + 1; int rightIdx = idx * 2 + 2; if(leftIdx < currSize && heap[leftIdx] > heap[idx]) { max = leftIdx; } if(rightIdx < currSize && heap[rightIdx] > heap[max]) { max = rightIdx; } if(max != idx) { // swap int temp = heap[max]; heap[max] = heap[idx]; heap[idx] = temp; heapifyRemove(max); } } public void insert(int itm) { if(currSize == capacity) { return; } heap[currSize] = itm; currSize++; heapifyAdd(currSize - 1); } public void remove() { if (currSize == 0) { return; } heap[0] = heap[currSize - 1]; currSize--; heapifyRemove(0); } public void print() { for(int i = 0; i < currSize; i++) { System.out.print(heap[i] + " "); } System.out.println(); } public static void main(String[] args) { MaxHeap maxHeap = new MaxHeap(10); maxHeap.insert(3); maxHeap.insert(1); maxHeap.insert(6); maxHeap.insert(5); maxHeap.insert(9); maxHeap.insert(8); maxHeap.print(); // Expected output: 9 5 8 1 3 6 maxHeap.remove(); maxHeap.print(); // Expected output: 8 5 6 1 3 } }
code/data_structures/src/maxHeap/maxheap.py
# Python3 implementation of Max Heap import sys class MaxHeap: def __init__(self, maxsize): self.maxsize = maxsize self.size = 0 self.Heap = [0] * (self.maxsize + 1) self.Heap[0] = sys.maxsize self.FRONT = 1 # Function to return the position of # parent for the node currently # at pos def parent(self, pos): return pos // 2 # Function to return the position of # the left child for the node currently # at pos def leftChild(self, pos): return 2 * pos # Function to return the position of # the right child for the node currently # at pos def rightChild(self, pos): return (2 * pos) + 1 # Function that returns true if the passed # node is a leaf node def isLeaf(self, pos): if pos >= (self.size//2) and pos <= self.size: return True return False # Function to swap two nodes of the heap def swap(self, fpos, spos): self.Heap[fpos], self.Heap[spos] = (self.Heap[spos], self.Heap[fpos]) # Function to heapify the node at pos def maxHeapify(self, pos): # If the node is a non-leaf node and smaller # than any of its child if not self.isLeaf(pos): if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or self.Heap[pos] < self.Heap[self.rightChild(pos)]): # Swap with the left child and heapify # the left child if (self.Heap[self.leftChild(pos)] > self.Heap[self.rightChild(pos)]): self.swap(pos, self.leftChild(pos)) self.maxHeapify(self.leftChild(pos)) # Swap with the right child and heapify # the right child else: self.swap(pos, self.rightChild(pos)) self.maxHeapify(self.rightChild(pos)) # Function to insert a node into the heap def insert(self, element): if self.size >= self.maxsize: return self.size += 1 self.Heap[self.size] = element current = self.size while (self.Heap[current] > self.Heap[self.parent(current)]): self.swap(current, self.parent(current)) current = self.parent(current) # Function to print the contents of the heap def Print(self): for i in range(1, (self.size // 2) + 1): print("PARENT : " + str(self.Heap[i]) + "LEFT CHILD : " + str(self.Heap[2 * i]) + "RIGHT CHILD : " + str(self.Heap[2 * i + 1])) # Function to remove and return the maximum # element from the heap def extractMax(self): popped = self.Heap[self.FRONT] self.Heap[self.FRONT] = self.Heap[self.size] self.size -= 1 self.maxHeapify(self.FRONT) return popped
code/data_structures/src/maxSubArray(KadaneAlgorithm)/KadaneAlgorithm.cpp
#include <iostream> #include <vector> using namespace std; int Kadane(vector<int>& arr) { int max_so_far = INT_MIN; int max_ending_here = 0; for (int i = 0; i < arr.size(); i++) { max_ending_here = max_ending_here + arr[i]; if (max_ending_here < 0) { max_ending_here = 0; } if (max_so_far < max_ending_here) { max_so_far = max_ending_here; } } return max_so_far; } int main(){ vector<int> a = {-2, -3, 4, -1, -2, 1, 5, -3}; cout << Kadane(a) << endl; return 0; } // Time Complexity: O(n) // Space Complexity: O(1) // Kadane algorithm is a simple algorithm for finding the maximum subarray sum in a given array.
code/data_structures/src/maxSubArray(KadaneAlgorithm)/KadaneAlgorithm.java
import java.util.*; class KadaneAlgorithm { static int maxSubarraySum(int a[], int n) { long max = a[0]; long sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; if (sum > max) max = sum; if (sum < 0) sum = 0; } return max; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int ans = maxSubarraySum(arr, n); System.out.println(ans); } }
code/data_structures/src/maxSubArray(KadaneAlgorithm)/Kadane_algorithm.py
def maxSubArraySum(a,size): max_so_far = a[0] - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far #a = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] a = [-2, -3, 4, -1, -2, 1, 5, -3] print("Maximum contiguous sum is", maxSubArraySum(a,len(a)))
code/data_structures/src/minHeap/minHeap.py
import sys class MinHeap: def __init__(self, maxsize): self.maxsize = maxsize self.size = 0 self.Heap = [0] * (self.maxsize + 1) self.Heap[0] = -1 * sys.maxsize self.FRONT = 1 def parent(self, pos): return pos // 2 def leftChild(self, pos): return 2 * pos def rightChild(self, pos): return (2 * pos) + 1 def isLeaf(self, pos): if pos >= (self.size//2) and pos <= self.size: return True return False def swap(self, fpos, spos): self.Heap[fpos], self.Heap[spos] = (self.Heap[spos], self.Heap[fpos]) def minHeapify(self, pos): if not self.isLeaf(pos): if (self.Heap[pos] > self.Heap[self.leftChild(pos)] or self.Heap[pos] > self.Heap[self.rightChild(pos)]): # Swap with the left child and heapify the left child if (self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]): self.swap(pos, self.leftChild(pos)) self.minHeapify(self.leftChild(pos)) # Swap with the right child and heapify the right child else: self.swap(pos, self.rightChild(pos)) self.minHeapify(self.rightChild(pos)) def insert(self, element): if self.size >= self.maxsize: return self.size += 1 self.Heap[self.size] = element current = self.size while (self.Heap[current] < self.Heap[self.parent(current)]): self.swap(current, self.parent(current)) current = self.parent(current) def Print(self): for i in range(1, (self.size // 2) + 1): print(" PARENT : " + str(self.Heap[i]) + " LEFT CHILD : " + str(self.Heap[2 * i]) + " RIGHT CHILD : " + str(self.Heap[2 * i + 1])) def extractMin(self): popped = self.Heap[self.FRONT] self.Heap[self.FRONT] = self.Heap[self.size] self.size -= 1 self.minHeapify(self.FRONT) return popped
code/data_structures/src/minqueue/minqueue.cpp
#include <deque> #include <iostream> using namespace std; //this is so the minqueue can be used with different types //check out the templeting documentation for more info about this //This version of minqueue is built upon the deque data structure template <typename T> class MinQueue { public: MinQueue() {} bool is_empty() const{ //utilizes the size parameter that deque provides if (q.size() > 0){ return false; //queue is not empty } return true; //queue is empty } int size() const{ return q.size(); } void pop(){ //Typically pop() should only change the queue state. It should not return the item //pop should only be called when there is an item in the //minQueue or else a deque exception will be raised if (q.size() > 0) { //perform check for an empty queue q.pop_front(); } } const T & top(){ return q.front(); } void push(const T &item){ q.push_back(item); //this forloop is to determine where in the minQueue the //new element should be placed for (int i = q.size()-1; i > 0; --i){ if (q[i-1] > q[i]){ swap(q[i-1], q[i]); } else{ break; } } } private: deque<T> q; }; int main(){ MinQueue<int> minQ; //Here is a testing of the algorithim cout << minQ.size() << endl; minQ.push(2); cout << minQ.size() << endl; cout << minQ.top() << endl; minQ.push(1); cout << minQ.top() << endl; minQ.pop(); cout << minQ.top() << endl; minQ.pop(); cout << minQ.size() << endl; minQ.push(10); cout << minQ.top() << endl; minQ.push(8); cout << minQ.top() << endl; minQ.push(7); cout << minQ.top() << endl; minQ.push(6); cout << minQ.top() << endl; minQ.push(1); cout << minQ.top() << endl; return 0; }
code/data_structures/src/other/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/data_structures/src/other/ways_to_swap.cpp
//DIFFERENT WAYS TO SWAP 2 NUMBERS:- #include<bits/stdc++.h> //it includes most of the headers files needed for basic programming using namespace std; int main() { int a = 10, b = 5, temp; // 1. USING THIRD VARIABLE temp = a; a = b; b = temp; // 2. USING ADDITION AND SUBTRACTION a = a + b; b = a - b; a = a - b; // 3. USING MULTIPLICATION AND DIVISON a = a * b; b = a / b; a = a / b; // 4. USING BITWISE XOR OPERATOR a = a ^ b; b = a ^ b; a = a ^ b; cout<<"after swapping a = "<<a<<" b = "<<b; //There are few more ways u can find by using the arithmetic operators //differently or by using XOR in single line like this (a ^= b ^= a ^= b;) //try on your and keep learning , good luck ! :) return 0; }
code/data_structures/src/prefix_sum_array/prefix_sum_array.py
def maximum_sum_subarray(arr, n): min_sum = 0 res = 0 prefixSum = [] prefixSum.append(arr[0]) for i in range(1, n): prefixSum.append(prefixSum[i-1] + arr[i]) for i in range(n): res = max(res, prefixSum[i] - min_sum) min_sum = min(min_sum, prefixSum[i]) return res n = int(input("Enter the size of the array: ")) a = [] for i in range(n): a.append(int(input("Enter element no. "+ str(i+1)+": "))) print("Result: ", maximum_sum_subarray(a, n))
code/data_structures/src/prefix_sum_array/prefix_sum_subarray.cpp
// Part of Cosmos by OpenGenus //Max Sum Subarray in O(n) #include <bits/stdc++.h> using namespace std; int maximumSumSubarray(int *arr, int n){ int minPrefixSum = 0; int res = numeric_limits<int>::min(); int prefixSum[n]; prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; } for (int i = 0; i < n; i++) { res = max(res, prefixSum[i] - minPrefixSum); minPrefixSum = min(minPrefixSum, prefixSum[i]); } return res; } int main(){ int n; cin>>n; // size of the array int arr[n]; for(int i=0;i<n;i++){ //input array cin>>arr[i]; } cout << "Result = " << maximumSumSubarray(arr, n) <<endl; return 0; }
code/data_structures/src/queue/README.md
# Queue Description --- A queue or FIFO (first in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: enqueue, the process of adding an element to the collection.(The element is added from the rear side) and dequeue, the process of removing the first element that was added. (The element is removed from the front side). It can be implemented by using both array and linked list. Functions --- - dequeue --Removes an item from the queue - enqueue() --Adds an item to the queue - front() --Returns the front element from the queue - size() --Returns the size of the queue ## Time Complexity - Enqueue - O(1) - Dequeue - O(1) - size - O(1) - front - O(n)
code/data_structures/src/queue/circular_buffer/circular_buffer.cpp
#include <iostream> #include <vector> template <typename T, long SZ> class circular_buffer { private: T* m_buffer; long m_index; public: circular_buffer() : m_buffer {new T[SZ]()} , m_index {0} { } ~circular_buffer() { delete m_buffer; } std::vector<T> get_ordered() noexcept { std::vector<T> vec; for (long i = 0; i < SZ; ++i) vec.push_back(m_buffer[(i + m_index) % SZ]); return vec; } void push(T x) noexcept { m_buffer[m_index] = x; m_index = (m_index + 1) % SZ; } }; int main() { circular_buffer<int, 4> buf; buf.push(1); buf.push(2); buf.push(3); buf.push(4); buf.push(5); buf.push(6); for (auto x : buf.get_ordered()) std::cout << x << std::endl; }
code/data_structures/src/queue/circular_buffer/circular_buffer.py
class CircularBuffer: __array = [] __size = 0 __idx = 0 def __init__(self, size): self.__array = [[] for _ in range(0, size)] self.__size = size def push(self, x): self.__array[self.__idx] = x self.__idx = (self.__idx + 1) % self.__size def get_ordered(self): retarr = [] for i in range(0, self.__size): retarr += [self.__array[(i + self.__idx) % self.__size]] return retarr buf = CircularBuffer(2) buf.push(1) buf.push(2) buf.push(3) for n in buf.get_ordered(): print(n)
code/data_structures/src/queue/double_ended_queue/deque_library_function.cpp
#include <iostream> #include <deque> using namespace std; void showdq (deque <int> g) { deque <int> :: iterator it; // Iterator to iterate over the deque . for (it = g.begin(); it != g.end(); ++it) cout << '\t' << *it; cout << "\n"; } int main () { deque <int> que; int option, x; do { cout << "\n\n DEQUEUE USING STL C++ "; cout << "\n 1.Insert front"; cout << "\n 2.Insert Back"; cout << "\n 3.Delete front"; cout << "\n 4.Delete Back"; cout << "\n 5.Display "; cout << "\n Enter your option : "; cin >> option; switch (option) { case 1: cout << "\n Enter number : "; cin >> x; que.push_front(x); break; case 2: cout << "\n Enter number : "; cin >> x; que.push_back(x); break; case 3: que.pop_front(); break; case 4: que.pop_back(); break; case 5: showdq(que); break; } } while (option != 6); return 0; }
code/data_structures/src/queue/double_ended_queue/double_ended_queue.c
#include <stdio.h> #include <conio.h> #define MAX 10 int deque[MAX]; int left =-1 ; int right = -1 ; void inputdeque(void); void outputdeque(void); void insertleft(void); void insertright(void); void deleteleft(void); void deleteright(void); void display(void); int main( ) { int option; printf("\n *****MAIN MENU*****"); printf("\n 1.Input restricted deque"); printf("\n 2.Output restricted deque"); printf("\n Enter your option : "); scanf("%d",&option); switch (option) { case 1 : inputdeque(); break; case 2 : outputdeque(); break; } return 0; } void inputdeque( ) { int option; do { printf("\n\n INPUT RESTRICTED DEQUE"); printf("\n 1.Insert at right"); printf("\n 2.Delete from left"); printf("\n 3.Delete from right"); printf("\n 4.Display"); printf("\n 5.Quit"); printf("\n Enter your option : "); scanf("%d",&option); switch (option) { case 1 : insertright(); break; case 2 : deleteleft(); break; case 3 : deleteright(); break; case 4 : display(); break; } } while (option!=5); } void outputdeque( ) { int option; do { printf("\n\n OUTPUT RESTRICTED DEQUE"); printf("\n 1.Insert at right"); printf("\n 2.Insert at left"); printf("\n 3.Delete from left"); printf("\n 4.Display"); printf("\n 5.Quit"); printf("\n Enter your option : "); scanf("%d",&option); switch(option) { case 1 : insertright(); break; case 2 : insertleft(); break; case 3 : deleteleft(); break; case 4 : display(); break; } } while (option!=5); } void insertright( ) { int val; printf("\n Enter the value to be added:"); scanf("%d", &val); if ( (left == 0 && right == MAX-1 ) || (left == right+1) ) { printf("\n OVERFLOW"); return; } if (left == -1) // Queue is Empty Inititally { left = 0; right = 0; } else { if (right == MAX-1) //right is at last position of queue right = 0; else right = right+1; } deque[right] = val ; } void insertleft( ) { int val; printf("\n Enter the value to be added:"); scanf("%d", &val); if( (left ==0 && right == MAX-1) || (left == right+1) ) { printf("\n OVERFLOW"); return; } if (left == -1) //If queue is initially empty { left = 0; right = 0; } else { if(left == 0) left = MAX - 1 ; else left = left - 1 ; } deque[left] = val; } void deleteleft( ) { if ( left == -1 ) { printf("\n UNDERFLOW"); return ; } printf("\n The deleted element is : %d", deque[left]); if (left == right) /*Queue has only one element */ { left = -1 ; right = -1 ; } else { if ( left == MAX - 1 ) left = 0; else left = left+1; } } void deleteright() { if ( left == -1 ) { printf("\n UNDERFLOW"); return ; } printf("\n The element deleted is : %d", deque[right]); if (left == right) /*queue has only one element*/ { left = -1 ; right = -1 ; } else { if (right == 0) right = MAX - 1 ; else right = right - 1 ; } } void display( ) { int front = left, rear = right; if ( front == -1 ) { printf("\n QUEUE IS EMPTY"); return; } printf("\n The elements of the queue are : "); if (front <= rear ) { while (front <= rear) { printf("%d ",deque[front]); front++; } } else { while (front <= MAX - 1) { printf("%d ", deque[front]); front++; } front = 0; while (front <= rear) { printf("%d ",deque[front]); front++; } } printf("\n"); }
code/data_structures/src/queue/double_ended_queue/double_ended_queue.cpp
#include <iostream> using namespace std; #define MAX 10 int deque[MAX]; int leftt = -1; int rightt = -1; void inputdeque(void); void outputdeque(void); void insertleft(void); void insertright(void); void deleteleft(void); void deleteright(void); void display(void); int main( ) { int option; cout << "\n *****MAIN MENU*****"; cout << "\n 1.Input restricted deque"; cout << "\n 2.Output restricted deque"; cout << "\n Enter your option : "; cin >> option; switch (option) { case 1: inputdeque(); break; case 2: outputdeque(); break; } return 0; } void inputdeque( ) { int option; do { cout << "\n\n INPUT RESTRICTED DEQUE"; cout << "\n 1.Insert at right"; cout << "\n 2.Delete from left"; cout << "\n 3.Delete from right"; cout << "\n 4.Display"; cout << "\n 5.Quit"; cout << "\n Enter your option : "; cin >> option; switch (option) { case 1: insertright(); break; case 2: deleteleft(); break; case 3: deleteright(); break; case 4: display(); break; } } while (option != 5); } void outputdeque( ) { int option; do { cout << "\n\n OUTPUT RESTRICTED DEQUE"; cout << "\n 1.Insert at right"; cout << "\n 2.Insert at left"; cout << "\n 3.Delete from left"; cout << "\n 4.Display"; cout << "\n 5.Quit"; cout << "\n Enter your option : "; cin >> option; switch (option) { case 1: insertright(); break; case 2: insertleft(); break; case 3: deleteleft(); break; case 4: display(); break; } } while (option != 5); } void insertright( ) { int val; cout << "\n Enter the value to be added:"; cin >> val; if ( (leftt == 0 && rightt == MAX - 1 ) || (leftt == rightt + 1) ) { cout << "\n OVERFLOW"; return; } if (leftt == -1) // Queue is Empty Inititally { leftt = 0; rightt = 0; } else { if (rightt == MAX - 1) //rightt is at last position of queue rightt = 0; else rightt = rightt + 1; } deque[rightt] = val; } void insertleft( ) { int val; cout << "\n Enter the value to be added:"; cin >> val; if ( (leftt == 0 && rightt == MAX - 1) || (leftt == rightt + 1) ) { cout << "\n OVERFLOW"; return; } if (leftt == -1) //If queue is initially empty { leftt = 0; rightt = 0; } else { if (leftt == 0) leftt = MAX - 1; else leftt = leftt - 1; } deque[leftt] = val; } void deleteleft( ) { if (leftt == -1) { cout << "\n UNDERFLOW"; return; } cout << "\n The deleted element is : " << deque[leftt]; if (leftt == rightt) /*Queue has only one element */ { leftt = -1; rightt = -1; } else { if (leftt == MAX - 1) leftt = 0; else leftt = leftt + 1; } } void deleteright() { if (leftt == -1) { cout << "\n UNDERFLOW"; return; } cout << "\n The element deleted is : " << deque[rightt]; if (leftt == rightt) /*queue has only one element*/ { leftt = -1; rightt = -1; } else { if (rightt == 0) rightt = MAX - 1; else rightt = rightt - 1; } } void display( ) { int front = leftt, rear = rightt; if (front == -1) { cout << "\n QUEUE IS EMPTY"; return; } cout << "\n The elements of the queue are : "; if (front <= rear) while (front <= rear) { cout << deque[front] << " "; front++; } else { while (front <= MAX - 1) { cout << deque[front] << " "; front++; } front = 0; while (front <= rear) { cout << deque[front] << " "; front++; } } cout << endl; //NEW LINE }
code/data_structures/src/queue/double_ended_queue/double_ended_queue.py
""" python programme for showing dequeue data sturcture in python """ """ class for queue type data structure having following methods""" class Queue: def __init__(self): self.array = [] # ''' initialise empty array ''' def front_enqueue(self, data): # ''' adding element from front ''' self.array.insert(0, data) def front_dequeue(self): # ''' deleting element from front ''' k = self.array[0] del self.array[0] def rear_dequeue(self): # ''' deleting element from rear ''' k = self.array.pop() print(k) def rear_enqueue(self, data): # ''' adding element from rear ''' self.array.append(data) def traverse(self): # ''' priting all array ''' print(self.array) queue = Queue() # ''' initialise Queue instance ''' queue.front_enqueue(5) queue.front_enqueue(4) queue.front_enqueue(3) queue.front_enqueue(2) queue.traverse() queue.front_dequeue() queue.traverse() queue.rear_enqueue(5) queue.rear_enqueue(4) queue.rear_enqueue(3) queue.rear_enqueue(2) queue.traverse() queue.rear_dequeue() queue.rear_dequeue() queue.traverse()
code/data_structures/src/queue/queue/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/queue/queue/queue.c
/* * C Program to Implement a Queue using an Array * Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #include <stdlib.h> #define MAX 50 int queue_array[MAX]; int rear = -1; int front = -1; void insert() { int add_item; if (rear == MAX - 1) { printf("Queue Overflow \n"); } else { /*If queue is initially empty */ if (front == -1) { front = 0; } printf("Insert the element in queue: "); scanf("%d", &add_item); rear = rear + 1; queue_array[rear] = add_item; } return; } void delete() { if (front == -1 || front > rear) { printf("Queue Underflow\n"); } else { printf("Element deleted from queue is: %d\n", queue_array[front]); front = front + 1; } return; } void display() { int i; if (front == -1) { printf("Queue is empty\n"); } else { printf("Queue is: \n"); for (i = front; i <= rear; i++) { printf("%d ", queue_array[i]); } printf("\n"); } return; } int main(void) { int choice; while (1) { printf("1. Insert element to queue\n"); printf("2. Delete element from queue\n"); printf("3. Display all elements of queue\n"); printf("4. Quit \n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: insert(); break; case 2: delete(); break; case 3: display(); break; case 4: exit(1); break; default: printf("Wrong choice\n"); break; } } return 0; }
code/data_structures/src/queue/queue/queue.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cassert> template <typename T> class Queue { private: int m_f; int m_r; std::size_t m_size; T * m_data; public: /*! \brief Constructs queue object with size. * \param sz Size of the queue. */ Queue( std::size_t sz = 10) : m_f( -1) , m_r( -1) , m_size( sz) , m_data( new T[sz]) { /* empty */ } /*! \brief Destructor */ ~Queue() { delete [] m_data; } /*! \brief Insert element at the end of the queue. * \param value Value to be inserted. */ void enqueue( const T& value ) { int prox_r = (m_r + 1) % m_size; if (prox_r == 0 or prox_r != m_f) { (m_f == -1) ? m_f = 0 : m_f = m_f; m_data[prox_r] = value; m_r = prox_r; } else assert(false); } /*! \brief Remove element at the end of the queue. */ void dequeue() { if (m_f != -1) { // If there is only 1 element, f = r = -1 if (m_f == m_r) m_f = m_r = -1; // If size > 1, f goes forward else m_f = (m_f + 1) % m_size; } else assert(false); } /*! \brief Get element at the beginning of the queue. * \return First element at the queue. */ T front() { if (m_f != -1) return m_data[m_f]; assert(false); } /*! \brief Check if queue is empty. * \return True if queue is empty, false otherwise. */ bool isEmpty() { return m_f == -1; } /*! \brief Clear content. */ void makeEmpty() { reserve(m_size); m_f = m_r = -1; m_size = 0; } /*! \brief Get size of the queue. * \return Size of the queue. */ T size() const { if (m_r == m_f) return 1; else if (m_r > m_f) return m_r - m_f + 1; else return m_f - m_r + 1; } /*! \brief Increase the storage capacity of the array to a value * that’s is greater or equal to 'new_cap'. * \param new_cap New capacity. */ void reserve( std::size_t new_cap ) { if (new_cap >= m_size) { //<! Allocates new storage area T *temp = new T[ new_cap ]; //<! Copy content to the new list for (auto i(0u); i < m_size; i++) temp[i] = m_data[i]; delete [] m_data; //<! Deallocate old storage area m_data = temp; //<! Pointer pointing to the new adress m_size = new_cap; //<! Updates size } } }; int main() { Queue<int> queue(3); queue.enqueue(5); assert(queue.front() == 5); assert(queue.size() == 1); queue.enqueue(4); queue.enqueue(3); //remove 2 elements queue.dequeue(); queue.dequeue(); assert( queue.size() == 1); //Insert one more queue.enqueue(2); assert( queue.size() == 3); return 0; }
code/data_structures/src/queue/queue/queue.cs
/** * Queue implementation using a singly-linked link. * Part of the OpenGenus/cosmos project. (https://github.com/OpenGenus/cosmos) * * A queue is a first-in first-out (FIFO) data structure. * Elements are manipulated by adding elements to the back of the queue and removing them from * the front. */ using System; namespace Cosmos_Data_Structures { public class Queue<T> { //Node is a element that holds the data of the current element plus a reference to the next element. //Used to implement the singly-linked list. private class Node { public T data; public Node next; public Node(T data, Node next) { this.data = data; this.next = next; } } //Queue variables //This queue is implemented as a singly-linked list, where the //front of the queue is the first element of the linked list, //and the back of the queue is the last element of the linked list. private Node front; private Node rear; public int Size { get; private set; } public Queue() { front = null; rear = null; Size = 0; } //Adds an element to the back of the queue. public void Enqueue(T element) { Node tmp = new Node(element, null); if(IsEmpty()) { front = tmp; rear = tmp; } else { rear.next = tmp; rear = tmp; } Size++; } //Removes and returns the element at the front of the queue. //Throws an exception if the queue is empty. public T Dequeue() { if(IsEmpty()) { throw new InvalidOperationException("Cannot dequeue on an empty queue!"); } Node tmp = front; front = tmp.next; Size--; if(front == null) { rear = null; } return tmp.data; } //Returns the element at the front of the queue. //Throws an exception if the queue is empty. public T Front() { if (IsEmpty()) { throw new InvalidOperationException("The queue is empty!"); } return front.data; } //Returns true if queue contains no elements, false otherwise. public bool IsEmpty() { return front == null && rear == null; } //Returns a string representation of the queue. public override string ToString() { Node tmp = front; string result = "Queue([Front] "; while(tmp != null) { result += tmp.data; tmp = tmp.next; if (tmp != null) { result += " -> "; } } result += " [Back])"; return result; } } //Stack testing methods/class. public class QueueTest { static void Main(string[] args) { var strQueue = new Queue<string>(); Console.WriteLine("Setting up queue..."); strQueue.Enqueue("Marth"); strQueue.Enqueue("Ike"); strQueue.Enqueue("Meta Knight"); Console.WriteLine(strQueue.ToString()); Console.WriteLine("Removing first element..."); strQueue.Dequeue(); Console.WriteLine(strQueue.ToString()); Console.ReadKey(); } } }
code/data_structures/src/queue/queue/queue.exs
defmodule Queue do def init, do: loop([]) def loop(queue) do receive do {:enqueue, {sender_pid, item}} -> queue = enqueue(queue, item) send sender_pid, {:ok, item} loop(queue) {:queue_next, {sender_pid}} -> {queue, next} = queue_next(queue) send sender_pid, {:ok, next} loop(queue) {:is_empty, {sender_pid}} -> is_empty = is_empty(queue) send sender_pid, {:ok, is_empty} loop(queue) {:size, {sender_pid}} -> size = size(queue) send sender_pid, {:ok, size} loop(queue) {:first_item, {sender_pid}} -> first_item = first_item(queue) send sender_pid, {:ok, first_item} loop(queue) {:last_item, {sender_pid}} -> last_item = last_item(queue) send sender_pid, {:ok, last_item} loop(queue) _ -> IO.puts "Invalid message" end end def enqueue(queue, item) do queue = queue ++ [item] queue end def queue_next([head | tail]) do {tail, head} end def is_empty(queue) do if queue |> length === 0 do true end false end def size(queue) do queue |> length end def first_item([head | _]) do head end def last_item(queue) do queue |> List.last end end defmodule RunQueue do def initialize_queue do queue = spawn(Queue, :init, []) send queue, {:enqueue, {self(), "hello"}} send queue, {:size, {self()}} send queue, {:enqueue, {self(), "message"}} send queue, {:queue_next, {self()}} send queue, {:enqueue, {self(), "another"}} send queue, {:is_empty, {self()}} send queue, {:first_item, {self()}} send queue, {:last_item, {self()}} manage() end def manage do receive do {:ok, message} -> IO.puts message _ -> IO.puts "Invalid message" end manage() end end RunQueue.initialize_queue
code/data_structures/src/queue/queue/queue.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" type Queue []int func (s *Queue) Push(v int) Queue { return append(*s, v) } func (s *Queue) Pop() Queue { length := len(*s) if length != 0 { return (*s)[1:] } return *s } func (s *Queue) Top() int { return (*s)[0] } func (s *Queue) Empty() bool { if len(*s) == 0 { return true } return false } func main() { queue := Queue{} fmt.Printf("Current Queue is %s, Is Queue empty ? %v \n", queue, queue.Empty()) fmt.Printf("Try to push 30 into Queue\n") queue = queue.Push(30) fmt.Printf("Current Queue is %v, top value is %v\n", queue, queue.Top()) fmt.Printf("Try to push 12 into Queue\n") queue = queue.Push(12) fmt.Printf("Try to push 34 into Queue\n") queue = queue.Push(34) fmt.Printf("Current Queue is %v, top value is %v\n", queue, queue.Top()) fmt.Printf("Current Queue is %v, Is Queue empty ? %v \n", queue, queue.Empty()) queue = queue.Pop() fmt.Printf("Current Queue is %v, top value is %v\n", queue, queue.Top()) queue = queue.Pop() queue = queue.Pop() fmt.Printf("Current Queue is %v, Is Queue empty ? %v\n", queue, queue.Empty()) }
code/data_structures/src/queue/queue/queue.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.ArrayList; class Queue<T> { private int maxSize; private ArrayList<T> queueArray; private int front; private int rear; private int nItems; public Queue(int size) { maxSize = size; queueArray = new ArrayList<>(); front = 0; rear = -1; nItems = 0; } public boolean insert(T data) { if (isFull()) return false; if (rear == maxSize - 1) //If the back of the queue is the end of the array wrap around to the front rear = -1; rear++; if(queueArray.size() <= rear) queueArray.add(rear, data); else queueArray.set(rear, data); nItems++; return true; } public T remove() { //Remove an element from the front of the queue if (isEmpty()) { throw new NullPointerException("Queue is empty"); } T temp = queueArray.get(front); front++; if (front == maxSize) //Dealing with wrap-around again front = 0; nItems--; return temp; } public T peekFront() { return queueArray.get(front); } public T peekRear() { return queueArray.get(rear); } public boolean isEmpty() { return (nItems == 0); } public boolean isFull() { return (nItems == maxSize); } public int getSize() { return nItems; } } public class Queues { public static void main(String args[]) { Queue<Integer> myQueue = new Queue<>(4); myQueue.insert(10); myQueue.insert(2); myQueue.insert(5); myQueue.insert(3); //[10(front), 2, 5, 3(rear)] System.out.println(myQueue.isFull()); //Will print true myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue //[10, 2(front), 5, 3(rear)] myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around // [7(rear), 2(front), 5, 3] System.out.println(myQueue.peekFront()); //Will print 2 System.out.println(myQueue.peekRear()); //Will print 7 } }
code/data_structures/src/queue/queue/queue.js
/* * Part of Cosmos by OpenGenus Foundation * */ function Queue(size_max) { data = new Array(size_max + 1); max = (size_max + 1); start = 0; end = 0; this.empty = () => { return start == end; } this.full = () => { return start == (end + 1) % max; } this.enqueue = (x) => { if (this.full()) { console.log("Queue full"); return false; } data[end] = x; end = (end + 1) % max; return true; } this.dequeue = () => { if (this.empty()) { console.log("Queue empty"); return; } x = data[start]; start = (start + 1) % max; return x; } this.top = () => { if (this.empty()) { console.log("Queue empty"); return; } return data[start]; } this.display = () => { cur = start while (cur != end) { console.log(data[cur]) cur = (cur + 1) % max } } } let q = new Queue(3); q.enqueue("a"); q.enqueue("b"); q.enqueue("c"); q.enqueue("d"); // Queue full q.display(); // a, b, c q.dequeue(); q.display(); // b, c q.dequeue(); q.dequeue(); q.dequeue(); // Queue empty q.enqueue("z"); q.display() // z
code/data_structures/src/queue/queue/queue.py
# Part of Cosmos by OpenGenus Foundation class Queue: def __init__(self, size_max): self.data = [None] * (size_max + 1) self.max = (size_max + 1) self.head = 0 self.tail = 0 def empty(self): return self.head == self.tail def full(self): return self.head == (self.tail + 1) % self.max def enqueue(self, x): if self.full(): print("Queue full") return False self.data[self.tail] = x self.tail = (self.tail + 1) % self.max return True def dequeue(self): if self.empty(): print("Queue empty") return None x = self.data[self.head] self.head = (self.head + 1) % self.max return x def top(self): if self.empty(): print("Queue empty") return None return self.data[self.head] def display(self): cur = self.head while cur != self.tail: print(self.data[cur]) cur = (cur + 1) % self.max print("Enter the size of Queue") n = int(input()) q = Queue(n) while True: print("Press E to enqueue an element") print("Press D to dequeue an element") print("Press P to display all elements of the queue") print("Press T to show top element of the queue") print("Press X to exit") opt = input().strip() if opt == "E": if q.full(): print("Queue is full") continue print("Enter the element") ele = int(input()) q.enqueue(ele) continue if opt == "D": ele = q.dequeue() if ele == None: print("Queue is empty") else: print("Element is", ele) if opt == "P": q.display() if opt == "T": print(q.top()) if opt == "X": break
code/data_structures/src/queue/queue/queue.rb
# Part of Cosmos by OpenGenus Foundation class Queue attr_accessor :items def initialize @items = [] end def enqueue(element) @items.push(element) end def dequeue @items.delete_at(0) end def empty? @items.empty? end def front @items.first end def back @items.last end end
code/data_structures/src/queue/queue/queue.swift
/* Part of Cosmos by OpenGenus Foundation */ public struct Queue<T> { private var elements: Array<T>; init() { self.elements = []; } init(arrayLiteral elements: T...) { self.elements = elements } public var front: T? { return elements.first } public var back: T? { return elements.last } public var size: Int { return elements.count } public var isEmpty: Bool { return elements.isEmpty } mutating public func enqueue(_ element: T) { elements.append(element) } mutating public func dequeue() -> T? { return self.isEmpty ? nil : elements.removeFirst() } }
code/data_structures/src/queue/queue/queue_vector.cpp
#include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation class Queue { private: // Vector for storing all of the values vector<int> _vec; public: void enqueue(int & p_put_obj); // Puts object at the end of the queue void dequeue(int & p_ret_obj); // Returns object at the start of the queue and removes from queue void peek(int & p_peek_obj); // Returns object at the start of the queue but doesn't remove it bool is_empty(); // Checks if the queue is full }; // Purpose: Put a value onto the end of the queue // Params : p_put_obj - reference to the object you want to enqueue void Queue::enqueue(int & p_put_obj) { // Use the inbuild push_back vector method _vec.push_back(p_put_obj); } // Purpose: Gets the value from the front of the queue // Params : p_ret_obj - Reference to an empty object to be overwritten by whatever is dequeued void Queue::dequeue(int & p_ret_obj) { // Set the value to what's in the start of the vector p_ret_obj = _vec[0]; // Delete the first value in the vector _vec.erase(_vec.begin()); } // Purpose: Checks if the queue is empty // Returns: True if the queue is empty bool Queue::is_empty() { return _vec.empty(); } // Purpose: Returns the value at the front of the queue, without popping it // Params : p_peek_obj - reference to the object to be overwritten by the data in the front of the queue void Queue::peek(int &p_peek_obj) { p_peek_obj = _vec[0]; } int main() { Queue q; int i = 0; int j = 1; q.enqueue(i); cout << "Enqueueing " << i << " to the queue" << endl; q.enqueue(j); cout << "Enqueueing " << j << " to the queue" << endl; int k, l, m; q.peek(m); cout << "Peeking into the queue, found " << m << endl; q.dequeue(k); cout << "Dequeueing, found " << k << endl; q.dequeue(l); cout << "Dequeueing, found " << l << endl; if (q.is_empty()) cout << "The queue is now empty" << endl; else cout << "The queue is not empty" << endl; }
code/data_structures/src/queue/queue_stream/queue_stream.cs
using System; namespace Cosmos_Data_Structures { /// <summary> /// QueueStream provides an alternative Queue implementation to High speed /// IO/Stream operations that works on multitheaded environment. /// Internally use 'circular array' in the implementation. /// </summary> [Serializable] public class QueueStream { byte[] _array = new byte[64]; // array in memory int _head; // head index int _tail; // tail index int _size; // Number of elements. /// <summary> /// Buffer size (maximum limit) for single stream operation (Default is 64 KB) /// </summary> const int BufferBlock = 1024 * 64; /// <summary> /// Get total bytes in queue /// </summary> public int Count { get { return _size; } } /// <summary> /// Remove all bytes in queue /// </summary> public virtual void Clear() { _head = 0; _tail = 0; _size = 0; } /// <summary> /// Remove all bytes in queue and discard waste memory to GC. /// </summary> public void Clean() { _head = 0; _tail = 0; _size = 0; _array = new byte[64]; } /// <summary> /// Adds a byte to the back of the queue. /// </summary> public virtual void Enqueue(byte obj) { if (_size == _array.Length) { SetCapacity(_size << 1); } _array[_tail] = obj; _tail = (_tail + 1) % _array.Length; _size++; } /// <summary> /// Removes and returns the byte at the front of the queue. /// </summary> /// <returns></returns> public byte Dequeue() { if (_size == 0) throw new InvalidOperationException("Invalid operation. Queue is empty!"); byte removed = _array[_head]; _head = (_head + 1) % _array.Length; _size--; return removed; } /// <summary> /// Returns the byte at the front of the queue. /// </summary> /// <returns></returns> public byte Front() { if (_size == 0) throw new InvalidOperationException("Invalid operation. Queue is empty!"); return _array[_head]; } /// <summary> /// Read and push stream bytes to queue. Can be multi-threaded. /// </summary> /// <param name="stream">The stream to push</param> /// <param name="maxSize">Maximum bytes size for this operation</param> /// <returns>Size of pushed bytes</returns> public int Enqueue(Stream stream, long maxSize = int.MaxValue) { if ((_size + BufferBlock) > _array.Length) { SetCapacity(Math.Max((_size + BufferBlock), _size << 1)); } var count = Math.Min(Math.Min((int)maxSize, BufferBlock), _array.Length - _tail); lock (_array) { count = stream.Read(_array, _tail, count); _tail = (_tail + count) % _array.Length; _size += count; } return count; } /// <summary> /// Pop and write stream bytes to queue. Can be multi-threaded. /// </summary> /// <param name="stream">The stream to pop</param> /// <param name="maxSize">Maximum bytes size for this operation</param> /// <returns>Size of popped bytes</returns> public int Dequeue(Stream stream, long maxSize = int.MaxValue) { if (_size == 0) return 0; // It's okay to be empty int count = Math.Min(Math.Min(BufferBlock, _size), Math.Min((int)maxSize, _array.Length - _head)); lock (_array) { stream.Write(_array, _head, count); _head = (_head + count) % _array.Length; _size -= count; } return count; } /// <summary> /// Set new capacity /// </summary> private void SetCapacity(int capacity) { lock (_array) { byte[] newarray = new byte[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; } } } }
code/data_structures/src/queue/queue_using_linked_list/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/queue/queue_using_linked_list/queue_using_linked_list.c
#include <stdio.h> #include <stdlib.h> /* @author AaronDills An implementation of a queue data structure using C and Linked Lists*/ /* Structure for a Node containing an integer value and reference to another Node*/ struct Node { int value; struct Node *next; }; /* Initalize global Nodes for the head and tail of the queue */ struct Node* head = NULL; struct Node* tail = NULL; /* Function declarations */ struct Node* createNode(); void enqueue(); void dequeue(); void printQueue(); int main(){ int choice = 0; while(1){ printf("1.Insert element to queue \n"); printf("2.Delete element from queue \n"); printf("3.Display all elements of queue \n"); printf("4.Quit \n"); printf("Please make a selection:"); scanf("%d", &choice); switch(choice){ case 1: enqueue(); break; case 2: dequeue(); break; case 3: printQueue(); break; case 4: exit(0); default: printf("Please enter a valid input\n"); } } } /* Creates a Node object with a value provided from user input */ struct Node* createNode(){ int userValue; printf("Enter the value you want to add: "); scanf("%d", &userValue); struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->value = userValue; newNode->next = NULL; return newNode; } /* Add a Node to the end of the queue */ void enqueue(){ if(head == NULL && tail == NULL){ head = tail = createNode(); }else{ tail-> next = createNode(); tail = tail->next; } } /* Remove front Node from queue */ void dequeue(){ struct Node* current = head; if(current == NULL){ printf("The queue is empty\n"); } if(current == tail){ head = NULL; tail = NULL; } else{ head = head->next; } free(current); } /* Iterate through queue and print Node values*/ void printQueue(){ struct Node* temp = head; while(temp != NULL){ printf("%d ", temp->value); temp = temp->next; } printf("\n"); }
code/data_structures/src/queue/queue_using_linked_list/queue_using_linked_list.cpp
#include <cassert> #include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; template <class T> class Queue { private: class Node { public: Node(const T &data, Node *next) : data(data), next(next) { } T data; Node *next; }; public: Queue(void); ~Queue(); void enqueue(const T &data); T dequeue(void); bool empty(void) const; int size(void) const; T &front(void); private: Node *head; Node *back; int items; }; template <class T> Queue<T>::Queue(void) : head(NULL) { items = 0; } template <class T> Queue<T>::~Queue() { while (head != NULL) { Node *tmpHead = head; head = head->next; delete tmpHead; } } template <class T> void Queue<T>::enqueue(const T &data) { Node *newNode = new Node(data, NULL); if (empty()) head = (back = newNode); else { back->next = newNode; back = back->next; } items++; } template <class T> T Queue<T>::dequeue(void) { assert(!empty()); Node *tmpHead = head; head = head->next; T data = tmpHead->data; items--; delete tmpHead; return data; } template <class T> bool Queue<T>::empty(void) const { return head == NULL; } template <class T> int Queue<T>::size(void) const { return items; } template <class T> T &Queue<T>::front(void) { assert(!empty()); return head->data; } int main() { Queue<int> queue; queue.enqueue(34); queue.enqueue(54); queue.enqueue(64); queue.enqueue(74); queue.enqueue(84); cout << queue.front() << endl; cout << queue.size() << endl; while (!queue.empty()) cout << queue.dequeue() << endl; cout << queue.size() << endl; cout << endl; return 0; }
code/data_structures/src/queue/queue_using_linked_list/queue_using_linked_list.java
class Node<T> //NODE CLASS { T data; Node<T> next; } // Part of Cosmos by OpenGenus Foundation //Queue Using linked list public class QueueUsingLL<T> { private Node<T> front; // Front Node private Node<T> rear; // Rear Node private int size; public int size(){ return size; } //Returns TRUE if queue is empty public boolean isEmpty(){ return size() == 0; } public T front() { return front.data; } public void enqueue(T element){ //to add an element in queue Node<T> newNode = new Node<>(); newNode.data = element; if(rear == null){ front = newNode; rear = newNode; } else{ rear.next = newNode; rear = newNode; } size++; } public T dequeue() { //to remove an element from queue T temp = front.data; if(front.next == null){ front = null; rear = null; } else{ front = front.next; } size--; return temp; } public static class QueueUse { //Main Function to implement Queue public static void main(String[] args) { QueueUsingLL<Integer> queueUsingLL=new QueueUsingLL<>(); for(int i=1;i<=10;i++) // Creates a dummy queue which contains integers from 1-10 { queueUsingLL.enqueue(i); } System.out.println("QUEUE :"); while (!queueUsingLL.isEmpty()) { System.out.println(queueUsingLL.dequeue()); } } } }
code/data_structures/src/queue/queue_using_linked_list/queue_using_linked_list.py
# Part of Cosmos by OpenGenus Foundation Queue = {"front": None, "back": None} class Node: def __init__(self, data, next): self.data = data self.next = next def Enqueue(Queue, element): N = Node(element, None) if Queue["back"] == None: Queue["front"] = N Queue["back"] = N else: Queue["back"].next = N Queue["back"] = Queue["back"].next def Dequeue(Queue): if Queue["front"] != None: first = Queue["front"] Queue["front"] = Queue["front"].next return first.data else: if Queue["back"] != None: Queue["back"] = None return "Cannot dequeue because queue is empty" Enqueue(Queue, "a") Enqueue(Queue, "b") Enqueue(Queue, "c") print(Dequeue(Queue))
code/data_structures/src/queue/queue_using_linked_list/queue_using_linked_list.rb
# Part of Cosmos by OpenGenus Foundation class LinkedQueue attr_reader :size def initialize @head = nil @tail = nil @size = 0 end def enqueue(element) new_node = Node.new(element) @size += 1 if @head @tail.next = new_node @tail = new_node else @head = new_node @tail = new_node end end def dequeue return nil unless @head removed = @head @head = @head.next @size -= 1 removed.element end def empty? @size == 0 end def front @head.element end end class Node attr_accessor :element attr_accessor :next def initialize(element) @element = element @next = nil end end queue = LinkedQueue.new puts queue.empty? queue.enqueue(1) puts queue.front queue.enqueue(3) queue.enqueue(4) queue.enqueue(2) queue.enqueue(0) puts queue.dequeue puts queue.dequeue puts queue.front puts format('Size: %d', queue.size)
code/data_structures/src/queue/queue_using_stack/queue_using_stack.c
#include<stdio.h> #include<stdlib.h> #include<assert.h> typedef struct stack { int top; unsigned capacity; int* A; } stack; typedef struct queue { struct stack* S1; struct stack* S2; } queue; /*STACK*/ stack* createStack(unsigned capacity) { stack* newStack = (stack*)malloc(sizeof(stack)); newStack->capacity = capacity; newStack->top = -1; newStack->A = (int*)malloc(capacity*sizeof(int)); return (newStack); } int isFull(stack* S) { return (S->top == S->capacity - 1); } int isEmpty(stack* S) { return (S->top == -1); } void push(stack* S, int item) { assert(!isFull(S)); S->A[++S->top] = item; } int pop(stack* S) { assert(!isEmpty(S)); return (S->A[S->top--]); } void deleteStack(stack* S) { free(S->A); free(S); } /*QUEUE*/ queue* createQueue(stack* S1, stack* S2) { queue* newQueue = (queue*)malloc(2*sizeof(stack*)); newQueue->S1 = S1; newQueue->S2 = S2; return (newQueue); } void enqueue(queue* Q, int item) { push(Q->S1, item); } int dequeue(queue* Q) { if (!isEmpty(Q->S2)) { return (pop(Q->S2)); } while (!isEmpty(Q->S1)) { push(Q->S2, pop(Q->S1)); } return (pop(Q->S2)); } void deleteQueue(queue* Q) { free(Q->S1); free(Q->S2); free(Q); } /*driver program*/ int main() { stack* S1 = createStack(100); stack* S2 = createStack(100); queue* Q = createQueue(S1, S2); enqueue(Q, 10); enqueue(Q, 20); enqueue(Q, 30); enqueue(Q, 40); /*Current appearance of Q : | 10 | 20 | 30 | 40 | */ printf("%d\n", dequeue(Q)); printf("%d\n", dequeue(Q)); printf("%d\n", dequeue(Q)); /*Current appearance of Q : | 40 | 10, 20, 30 have been dequeued*/ enqueue(Q, 5); enqueue(Q, 8); /*Current appearance of Q : | 40 | 5 | 8 | */ printf("%d\n", dequeue(Q)); printf("%d\n", dequeue(Q)); /*Current appearance of Q : | 8 | */ deleteQueue(Q); return 0; }
code/data_structures/src/queue/queue_using_stack/queue_using_stack.cpp
#include <iostream> #include <stack> using namespace std; // Part of Cosmos by OpenGenus Foundation // queue data structure using two stacks class queue { private: stack<int> s1, s2; public: void enqueue(int element); int dequeue(); void displayQueue(); }; // enqueue an element to the queue void queue :: enqueue(int element) { s1.push(element); } // dequeue the front element int queue :: dequeue() { // transfer all elements of s1 into s2 if (s1.empty() && s2.empty()) return 0; while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } // pop and store the top element from s2 int ret = s2.top(); s2.pop(); // transfer all elements of s2 back to s1 while (!s2.empty()) { s1.push(s2.top()); s2.pop(); } return ret; } //display the elements of the queue void queue :: displayQueue() { cout << "\nDisplaying the queue :-\n"; while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } while (!s2.empty()) { cout << s2.top() << " "; s1.push(s2.top()); s2.pop(); } } // main int main() { queue q; int exit = 0; int enqueue; char input; while (!exit) { cout << "Enter e to enqueue,d to dequeue,s to display queue,x to exit: "; cin >> input; if (input == 'e') { cout << "Enter number to enqueue: "; cin >> enqueue; q.enqueue(enqueue); } if (input == 'd') q.dequeue(); if (input == 's') { q.displayQueue(); cout << endl; } if (input == 'x') break; } return 0; }
code/data_structures/src/queue/queue_using_stack/queue_using_stack.java
import java.util.NoSuchElementException; import java.util.Stack; /** * Implements https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html * Big O time complexity: O(n) * Part of Cosmos by OpenGenus Foundation */ class Queue<T> { Stack<T> temp = new Stack<>(); Stack<T> value = new Stack<>(); public Queue<T> enqueue(T element) { add(element); return this; } public T dequeue() { return remove(); } /** * * Inserts the specified element into this queue if it is possible to do so immediately without violating capacity * restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available. * @param item the element to add * @return true upon success, throwing an IllegalStateException if no space is currently available. */ public boolean add(T item) { if (value.isEmpty()) { value.push(item); } else { while (!value.isEmpty()) { temp.push(value.pop()); } value.push(item); while (!temp.isEmpty()) { value.push(temp.pop()); } } return true; } /** * Inserts the specified element into this queue if it is possible to do so immediately without violating capacity * restrictions. * @param element the element to add * @return true if the element was added to this queue, else false */ public boolean offer(T element) { try { return add(element); } catch (Exception ex) { //failed to add, return false return false; } } /** * Retrieves and removes the head of this queue. * This method differs from poll only in that it throws an exception if this queue is empty. * @return the head of this queue. * @throws NoSuchElementException if this queue is empty */ public T remove() throws NoSuchElementException{ try { return value.pop(); } catch (Exception ex) { throw new NoSuchElementException(); } } /** * Retrieves and removes the head of this queue, or returns null if this queue is empty. * This method differs from peek only in that it throws an exception if this queue is empty. * @return the head of this queue, or returns null if this queue is empty. */ public T poll() { try { return remove(); } catch (Exception ex) { //failed to remove, return null return null; } } /** * Retrieves, but does not remove, the head of this queue. * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ public T element() throws NoSuchElementException{ try { return value.peek(); } catch (Exception ex) { throw new NoSuchElementException(); } } /** * Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. * @return the head of this queue, or returns null if this queue is empty. */ public T peek() { try { return value.peek(); } catch (Exception ex) { //failed to remove, return null return null; } } /** * Methods standard queue inherits from interface java.util.Collection */ public boolean isEmpty() { return value.isEmpty(); } } public class QueueStacks { /** * Main function to show the use of the queue */ public static void main(String[] args) { Queue<Integer> queueStacks = new Queue<>(); for(int i=1; i<=10; i++) // Creates a dummy queue which contains integers from 1-10 { queueStacks.enqueue(i); } System.out.println("QUEUE :"); while (!queueStacks.isEmpty()) { System.out.println(queueStacks.dequeue()); } } }
code/data_structures/src/queue/queue_using_stack/queue_using_stack.py
# Part of Cosmos by OpenGenus Foundation class Stack: def __init__(self): self.items = [] def push(self, x): self.items.append(x) def pop(self): return self.items.pop() def size(self): return len(self.items) def is_empty(self): return self.size() == 0 class Queue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def enqueue(self, p): self.s1.push(p) def dequeue(self): # pop all elements in s1 onto s2 while not self.s1.is_empty(): self.s2.push(self.s1.pop()) # pop all elements of s1 return_value = self.s2.pop() # re pop all elements of s2 onto s1 while not self.s2.is_empty(): self.s1.push(self.s2.pop()) return return_value if __name__ == "__main__": from random import choice a = Queue() l = [choice(range(1, 500)) for i in range(1, 10)] print(l) for i in l: a.enqueue(i) for i in range(len(l)): print("Dequeued:", a.dequeue())
code/data_structures/src/queue/queue_using_stack/queue_using_stack.sh
#!/bin/bash #Function to start the Program function start(){ echo -e "\t\t1.[E]nter in Queue" echo -e "\t\t2. [D]elete from Queue" echo -e "\t\t3. [T]erminate the Program" read OP } # Function to Insert Values Into Queue function insert(){ read -p "How many Elements would you like to Enter " NM for ((a=0;$a<$NM;a++)) do read -p "Enter The value : " arr[$a] done echo -e "New Queue is ${arr[@]}\n" } #Function to Delete Values From Queue #Here arr is one stack and arr2 is another stack function delete(){ read -p "How Many Elements to be Deleted : " ED c=`echo "${arr[@]}"` int=`echo "${#arr[@]}"` int=$[$int -1] if [[ -z "$c" ]] then echo -e "Queue is Empty\n" fi if [[ "$ED" -gt "$int" ]] then echo -e "The Number of Elements to be Deleted is Greater than the Number of elements in Queue\n" else if [[ -n "$c" ]] then ed=$[$int-$ED] q=0 while [ $ed -ne 0 ] do arr2[q]=`echo "${arr[$int]}"` q=$[$q+1] int=$[$int-1] ed=$[$ed-1] done for((i=0;$i<=$int;i++)) do echo -e "Delete Elements are ${arr[$i]}\n" unset arr[$i] done echo -e "New Queue ${arr2[@]}\n " else echo -e "Empty Queue\n" fi fi } while : do start case $OP in "E"|"e") clear insert ;; "D"|"d") clear delete ;; "T"|"t") clear break ;; *) clear echo -e "Please Choose Again\nEnter The First Letter of each Choice that is either 'E','D' or 'T'\n" ;; esac done
code/data_structures/src/queue/reverse_queue/reverse_queue.cpp
#include <iostream> #include <stack> #include <queue> using namespace std; // Part of Cosmos by OpenGenus Foundation void print(queue<int> q) { while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl; } int main() { queue<int> q; stack<int> s; //build the queue for (int i = 0; i <= 5; i++) q.push(i); //print the queue print(q); //empty the queue into stack while (!q.empty()) { s.push(q.front()); q.pop(); } //empty stack into queue while (!s.empty()) { q.push(s.top()); s.pop(); } //print the reversed queue print(q); return 0; }
code/data_structures/src/queue/reverse_queue/reverse_queue.go
// Part of Cosmos by OpenGenus Foundation package main /* Exptected output: Current Queue is [], Is Queue empty ? true Try to push 30 into Queue Try to push 12 into Queue Try to push 34 into Queue Try to push 2 into Queue Try to push 17 into Queue Try to push 88 into Queue Reverse Queue 88 17 2 34 12 30 */ import "fmt" type Queue []int func (q *Queue) Push(v int) { *q = append(*q, v) } func (q *Queue) Pop() { length := len(*q) if length != 0 { (*q) = (*q)[1:] } } func (q *Queue) Top() int { return (*q)[0] } func (q *Queue) Empty() bool { if len(*q) == 0 { return true } return false } func (q *Queue) Reverse() { for i, j := 0, len(*q)-1; i < j; i, j = i+1, j-1 { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] } } func main() { queue := Queue{} fmt.Printf("Current Queue is %s, Is Queue empty ? %v \n", queue, queue.Empty()) fmt.Printf("Try to push 30 into Queue\n") queue.Push(30) fmt.Printf("Try to push 12 into Queue\n") queue.Push(12) fmt.Printf("Try to push 34 into Queue\n") queue.Push(34) fmt.Printf("Try to push 2 into Queue\n") queue.Push(2) fmt.Printf("Try to push 17 into Queue\n") queue.Push(17) fmt.Printf("Try to push 88 into Queue\n") queue.Push(88) fmt.Println("Reverse Queue") queue.Reverse() for !queue.Empty() { fmt.Printf("%d ", queue.Top()) queue.Pop() } fmt.Printf("\n") }
code/data_structures/src/queue/reverse_queue/reverse_queue.java
import java.util.*; public class reverse_queue { // Part of Cosmos by OpenGenus Foundation //method to print contents of queue public static void print(Queue<Integer> queue) { for(int x : queue) { System.out.print(x + " "); } System.out.print("\n"); } public static void main (String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); Stack<Integer> stack = new Stack<Integer>(); //build the queue with 1..5 for(int i=0; i<=5; i++) { queue.add(i); } //print the queue print(queue); //move queue contents to stack while(!queue.isEmpty()) { stack.push(queue.poll()); } //move stack contents back to queue while(!stack.isEmpty()) { queue.add(stack.pop()); } //reprint reversed queue print(queue); } }
code/data_structures/src/queue/reverse_queue/reverse_queue.py
# Part of Cosmos by OpenGenus Foundation. # Make a new Queue class with list. class Queue: def __init__(self, size_max): self.__max = size_max self.__data = [] # Adds an item to the end of the queue. def enqueue(self, x): if len(self.__data) == self.__max: print("Queue is full") else: self.__data.append(x) # Removes the first item of the queue without returning it. def dequeue(self): if len(self.__data) == 0: print("Queue is empty") else: self.__data.pop(0) # Returns the first item of the queue. def front(self): if len(self.__data) == 0: print("Queue is empty") return False return self.__data[0] # Returns the size of the queue, not the maximum size. def size(self): return len(self.__data) # Returns the maximum size that the queue can hold def capacity(selfs): return len(self.__max) # Return all items from queue in list. def get(queue): lst = [] while queue.size() > 0: lst.append(queue.front()) queue.dequeue() # I don't the items to be removed, so I add them again. # But if you want, you can remove/comment it out. for item in lst: queue.enqueue(item) return lst # Return reversed queue. def reverse(queue): # Reverse the return value, which is in list type, from get() method temp = get(queue)[::-1] # Add all items from reversed list to rev rev = Queue(len(temp)) for item in temp: rev.enqueue(item) return rev # Print formatted output. def display(queue): # First, it will show you the original queue. print("Original queue: {}".format(get(queue))) # Then, it will show the reversed one. print("Reversed queue: {}\n".format(get(reverse(queue)))) # Add all item in list to queue. def listToQueue(lst): queue = Queue(len(lst)) for item in lst: queue.enqueue(item) return queue # Examples. int_arr = [1, 3, 2, 5, 4] string_arr = ["alpha", "beta", "gamma", "echo", "delta"] double_arr = [1.1, 3.2, 1.2, 5.4, 4.3] mix_arr = [1, "alpha", 2.1, True, "D"] # Collect all example in one list. examples = [int_arr, string_arr, double_arr, mix_arr] # First, each example will be transfered from list to queue, # then it will be printed as output. for item in examples: display(listToQueue(item))
code/data_structures/src/queue/reverse_queue/reverse_queue.swift
/* Part of Cosmos by OpenGenus Foundation */ // Queue implementation public struct Queue<T> { private var elements: Array<T>; init() { self.elements = []; } init(arrayLiteral elements: T...) { self.elements = elements } public var front: T? { return elements.first } public var back: T? { return elements.last } public var size: Int { return elements.count } public var isEmpty: Bool { return elements.isEmpty } mutating public func enqueue(_ element: T) { elements.append(element) } mutating public func dequeue() -> T? { return self.isEmpty ? nil : elements.removeFirst() } } // Reverse method implementation extension Queue { public func printElements() { for x in elements { print(x, terminator: " ") } print() } mutating public func reverse() { var items = Array<T>() while !self.isEmpty { items.append(self.dequeue()!) } while !items.isEmpty { self.enqueue(items.removeLast()) } } } func test() { var queue = Queue<Int>(arrayLiteral: 1, 3, 2, 5) print("Original queue:") queue.printElements() queue.reverse() print("Reversed queue:") queue.printElements() } test()
code/data_structures/src/sparse_table/sparse_table.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cassert> #include <functional> #include <iomanip> #include <cmath> template<typename T, std::size_t S> class SparseTable { public: /*! * \brief Builds a sparse table from a set of static data. It is the user responsibility to delete any allocated memory * \param data The static data * \param f The function to be applied on the ranges * \param defaultValue The default value for the function (e.g. INFINITY for Range Minimum Queries) */ SparseTable(const T* const data, const std::function<T(T, T)>& f, T defaultValue) : f_{f}, data_{data}, defaultValue_{defaultValue} { initializeSparseTable(); } /*! * \returns The number of elements in the set of static data */ constexpr std::size_t size() const { return S; } /*! * \brief Queries the range [l, r] in 0(1) time * It can only be used if the function is idempotent(e.g. Range Minimum Queries) * \param l The starting index of the range to be queried * \param r The end index of the range to be queried * \returns The result of the function f applied to the range [l, r] */ const T queryRangeIdempotent(int l, int r) { assert(l >= 0 && r < S); if (l > r) return defaultValue_; std::size_t length = r - l + 1; return f_(sparseTable_[logs_[length]][l], sparseTable_[logs_[length]][r - (1 << logs_[length]) + 1]); } /*! * \brief Queries the range [l, r] in O(log(n)) time * It can be used for any function(e.g. Range Sum Queries) * \param l The starting index of the range to be queried * \param r The end index of the range to be queried * \returns The result of the function f applied to the range [l, r] */ const T queryRange(int l, int r) { assert(l >= 0 && r < S); T ans = defaultValue_; while (l < r) { ans = f_(ans, sparseTable_[logs_[r - l + 1]][l]); l += (1 << logs_[r - l + 1]); } return ans; } private: T sparseTable_ [((int)std::log2(S)) + 1][S]; const T* const data_; const std::function<T(T, T)> f_; T defaultValue_; int logs_ [S + 1]; /* * Computes and stores log2(i) for all i from 1 to S */ void precomputeLogs() { logs_[1] = 0; for (int i = 2; i <= S; i++) logs_[i] = logs_[i / 2] + 1; } /* * Creates a sparse table from a set of static data * This precomputation takes O(nlog(n)) time */ void initializeSparseTable() { precomputeLogs(); for (int i = 0; i <= logs_[S] + 1; i++) { for (int j = 0; j + (1 << i) <= S; j++) { if (i == 0) sparseTable_[i][j] = data_[j]; else sparseTable_[i][j] = f_(sparseTable_[i-1][j], sparseTable_[i-1][j + (1 << (i - 1))]); } } } }; int main() { // Sparse table for range sum queries with integers { int data [] = { 4, 4, 6, 7, 8, 10, 22, 33, 5, 7 }; std::function<int(int, int)> f = [](int a, int b) { return a + b; }; SparseTable<int, 10> st(data, f, 0); std::cout << st.queryRange(3, 6) << std::endl; std::cout << st.queryRange(6, 9) << std::endl; std::cout << st.queryRange(0, 9) << std::endl; } // Sparse table for range minimum queries with doubles { double data [] = { 3.4, 5.6, 2.3, 9.4, 4.2 }; std::function<double(double, double)> f = [](double a, double b) { return std::min(a, b); }; SparseTable<double, 5> st(data, f, 10e8); std::setprecision(4); std::cout << st.queryRangeIdempotent(0, 3) << std::endl; std::cout << st.queryRangeIdempotent(3, 4) << std::endl; std::cout << st.queryRangeIdempotent(0, 4) << std::endl; } return 0; }
code/data_structures/src/stack/Quick_sort_usingSack/quick_sort.cpp
#include <iostream> #include <stack> using namespace std; int arr[] = {4, 1, 5, 3, 50, 30, 70, 80, 28, 22}; stack<int> higherStack, lowerStack; void displayArray(); void quick_sort(int lower, int higher); void partition(int lower, int higher); int main() { lowerStack.push(0); higherStack.push(9); quick_sort(0,9); displayArray(); } void quick_sort(int lower, int higher) { if (sizeof(arr) / 4 <= 1) { return; } while (!lowerStack.empty()) { partition(lower, higher); quick_sort(lowerStack.top(), higherStack.top()); lowerStack.pop(); higherStack.pop(); } } void displayArray() { for (int i = 0; i < 10; i++) { cout << arr[i] << " "; } cout << endl; } void partition(int lower, int higher) { int i = lower; int j = higher; int pivot = arr[lower]; while (i <= j) { while (pivot <= arr[i] && i<=higher) { i++; } while (pivot > arr[j] && j<=lower) { j--; } if(i>j) swap(arr[i], arr[j]); } swap(arr[j], arr[lower]); lowerStack.push(lower); lowerStack.push(j + 1); higherStack.push(j - 1); higherStack.push(higher); }
code/data_structures/src/stack/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/abstract_stack/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/abstract_stack/cpp/array_stack.java
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Stack<E> { private E[] arr = null; private int CAP; private int top = -1; private int size = 0; @SuppressWarnings("unchecked") public Stack(int cap) { this.CAP = cap; this.arr = (E[]) new Object[cap]; } public E pop() { if(this.size == 0) return null; this.size--; E result = this.arr[top]; //prevent memory leaking this.arr[top] = null; this.top--; return result; } public boolean push(E e) { if (!isFull()) return false; this.size++; this.arr[++top] = e; return false; } public boolean isFull() { if (this.size == this.CAP) return false; return true; } public String toString() { if(this.size == 0) return null; StringBuilder sb = new StringBuilder(); for(int i = 0; i < this.size; i++) sb.append(this.arr[i] + ", "); sb.setLength(sb.length()-2); return sb.toString(); } } class Stack1 { public static void main(String[] args) { Stack<String> stack = new Stack<String>(11); stack.push("hello"); stack.push("world"); System.out.println(stack); stack.pop(); System.out.println(stack); stack.pop(); System.out.println(stack); } }
code/data_structures/src/stack/abstract_stack/cpp/array_stack/array_stack.cpp
#include <iostream> #include "../istack.h" #include "arraystack.h" int main() { int s; IStack<int> *stack = new ArrayStack<int>(); try { stack->peek(); } catch (char const *e) { std::cout << e << std::endl << std::endl; } stack->push(20); std::cout << "Added 20" << std::endl; IStack<int> *stack2 = stack; std::cout << "1 " << std::endl; std::cout << stack->toString() << std::endl; std::cout << "2 " << std::endl; std::cout << stack2->toString() << std::endl; stack->push(30); std::cout << "Added 30" << std::endl; std::cout << std::endl << std::endl << stack->toString() << std::endl << std::endl; s = stack->peek(); std::cout << "First element is now: " << s << std::endl; std::cout << "removed: " << stack->pop() << std::endl; s = stack->peek(); std::cout << "First element is now: " << s << std::endl; delete stack; return 0; }
code/data_structures/src/stack/abstract_stack/cpp/array_stack/array_stack.h
#ifndef ARRAYSTACH_H #define ARRAYSTACK_H #include <string> #include <sstream> #include "../istack.h" template<typename T> class ArrayStack : public IStack<T> { private: int capacity; int top; T **elements; void expandArray(); public: ArrayStack(int capacity = 10); ArrayStack(const ArrayStack& stack); ~ArrayStack(); ArrayStack& operator=(const ArrayStack& right); void push(const T& element); T pop(); T peek() const; bool isEmpty() const; std::string toString() const; }; template<typename T> void ArrayStack<T>::expandArray() { if (this->capacity <= this->top) { T ** temp = this->elements; this->capacity = this->capacity * 2; this->elements = new T*[this->capacity]; for (int i = 0; i < this->top; i++) { this->elements[i] = temp[i]; } for (int i = this->top; i < this->capacity; i++) { this->elements[i] = nullptr; } delete [] temp; temp = nullptr; } } template<typename T> ArrayStack<T>::ArrayStack(int capacity) { this->capacity = capacity; this->top = 0; this->elements = new T*[this->capacity]; for (int i = 0; i < this->capacity; i++) { this->elements[i] = nullptr; } } template<typename T> ArrayStack<T>::ArrayStack(const ArrayStack& stack) { this->top = stack.top; this->capacity = stack.capacity; if (stack.elements != nullptr) { this->elements = new T*[this->capacity]; for (int i = 0; i < this->top; i++) { this->elements[i] = new T(*stack.elements[i]); } for (int i = this->top; i < this->capacity; i++) { this->elements[i] = nullptr; } } } template<typename T> ArrayStack<T>::~ArrayStack() { for (int i = 0; i < this->top; i++) { delete this->elements[i]; } delete [] this->elements; } template<typename T> ArrayStack<T>& ArrayStack<T>::operator=(const ArrayStack& right) { if (this == &right) { throw "Self-assigning at operator= "; } this->top = right.top; this->capacity = right.capacity; for (int i = 0; i < this->top; i++) { delete this->elements[i]; } delete [] this->elements; if (right.elements != nullptr) { this->elements = new T*[this->capacity]; for (int i = 0; i < this->top; i++) { this->elements[i] = new T(*right.elements[i]); } for (int i = this->top; i < this->capacity; i++) { this->elements[i] = nullptr; } } return *this; } template<typename T> void ArrayStack<T>::push(const T& element) { this->expandArray(); this->elements[this->top] = new T(element); this->top++; } template<typename T> T ArrayStack<T>::pop() { if (this->isEmpty()) { throw "The stack is empty."; } T temp = *this->elements[this->top - 1]; delete this->elements[this->top - 1]; this->elements[this->top - 1] = nullptr; this->top--; return temp; } template<typename T> T ArrayStack<T>::peek() const { if (this->isEmpty()) { throw "The stack is empty."; } return *this->elements[this->top - 1]; } template<typename T> bool ArrayStack<T>::isEmpty() const { return this->elements[0] == nullptr; } template<typename T> std::string ArrayStack<T>::toString() const { std::stringstream stream; if (!this->isEmpty()) { stream << "The stack looks like; " << std::endl; for (int i = 0; i < this->top; i++) { stream << i << " : " << '[' << *this->elements[i] << ']' << std::endl; } } else { stream << "The stack is empty" << std::endl; } return stream.str(); } #endif
code/data_structures/src/stack/abstract_stack/cpp/is_stack.h
#ifndef ISTACK_H #define ISTACK_H #include <string> #include <sstream> template <typename T> class IStack { public: virtual ~IStack() {}; /** * Add an element to stack */ virtual void push(const T& element) = 0; /** * Remove an element from stack */ virtual T pop() = 0; /** * Retuns the fist element in the stack */ virtual T peek() const = 0; /** * Returns if the stack is empty */ virtual bool isEmpty() const = 0; /** * Gets a string-representation of the stack */ virtual std::string toString() const = 0; }; #endif
code/data_structures/src/stack/abstract_stack/is_stack.h
#ifndef ISTACK_H #define ISTACK_H #include <string> #include <sstream> template <typename T> class IStack { public: virtual ~IStack() {}; /** * Add an element to stack */ virtual void push(const T& element) = 0; /** * Remove an element from stack */ virtual T pop() = 0; /** * Retuns the fist element in the stack */ virtual T peek() const = 0; /** * Returns if the stack is empty */ virtual bool isEmpty() const = 0; /** * Gets a string-representation of the stack */ virtual std::string toString() const = 0; }; #endif
code/data_structures/src/stack/balanced_expression/balanced_expression.c
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct stack { char data; struct stack* next; } stack; void push(stack** top, char data) { stack* new = (stack*) malloc(sizeof(stack)); new->data = data; new->next = *top; *top = new; } char peek(stack* top) { return ( top -> data ); } int empty(stack* top) { return (top == NULL); } void pop(stack** top) { stack* temp = *top; *top = (*top)->next; free(temp); temp = NULL; } int checkBalanced(char *s) { int len = strlen(s); if (len % 2 != 0) return 0; stack *head = NULL; for (int i = 0;i < len ;i++) { if (s[i] == '{' || s[i] == '[' || s[i] == '(') { push(&head, s[i]); } else { char temp = peek(head); if (s[i] == '}' && temp == '{') pop(&head); else if (s[i] == ']' && temp == '[') pop(&head); else if (s[i] == ')' && temp == '(') pop(&head); else return 0; } } return (empty(head)); } int main() { char *s = (char*) malloc(sizeof(char) * 100); printf("Enter the expression\n"); scanf("%[^\n]s" , s); int res = checkBalanced(s); if (res) printf("Expression is valid\n"); else printf("Expression is not valid\n"); return 0; }
code/data_structures/src/stack/balanced_expression/balanced_expression.cpp
// Stack | Balance paraenthesis | C++ // Part of Cosmos by OpenGenus Foundation #include <iostream> #include <stack> bool checkBalanced(string s) { // if not in pairs, then not balanced if (s.length() % 2 != 0) return false; std::stack <char> st; for (const char: s) { //adding opening brackets to stack if (s[i] == '{' || s[i] == '[' || s[i] == '(') st.push(s[i]); //if opening brackets encounter, push into stack else { // checking for each closing bracket, if there is an opening bracket in stack char temp = st.top(); if (s[i] == '}' && temp == '{') st.pop(); else if (s[i] == ']' && temp == '[') st.pop(); else if (s[i] == ')' && temp == '(') st.pop(); else return false; } } return st.empty(); } int main() { std::string s; std::cin >> s; bool res = checkBalanced(s); if (res) std::cout << "Expression is balanced"; else std::cout << "Expression is not balanced"; return 0; }
code/data_structures/src/stack/balanced_expression/balanced_expression.java
import java.util.*; class BalancedExpression { public static void main(String args[]) { System.out.println("Balanced Expression"); Scanner in = new Scanner(System.in); String input = in.next(); if (isExpressionBalanced(input)) { System.out.println("The expression is balanced"); } else { System.out.println("The expression is not balanced"); } static boolean isExpressionBalanced(String input) { Stack stack = new Stack(); for (int i=0; i<input.length(); i++) { if (input.charAt(i) == '(' || input.charAt(i) == '{'|| input.charAt(i) == '[') { stack.push(input.charAt(i)); } if (input.charAt(i) == ')' || input.charAt(i) == '}'|| input.charAt(i) == ']') { if (stack.empty()) { return false; } char top_char = (char) stack.pop(); if ( (top_char == '(' && input.charAt(i) != ')') || (top_char == '{' && input.charAt(i) != '}') || (top_char == '[' && input.charAt(i) != ']') ) { return false; } } } return stack.empty(); } } }
code/data_structures/src/stack/balanced_expression/balanced_expression.py
OPENING = '(' def is_balanced(parentheses): stack = [] for paren in parentheses: if paren == OPENING: stack.append(paren) else: try: stack.pop() except IndexError: # too many closing parens return False return len(stack) == 0 # false if too many opening parens s = '((()))' if is_balanced(s): print("string is balanced") else: print("string is unbalanced")
code/data_structures/src/stack/infix_to_postfix/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/infix_to_postfix/infix_to_postfix.c
#include <stdio.h> #include <string.h> #include <stdlib.h> // Part of Cosmos by OpenGenus Foundation // Stack type struct Stack { int top; unsigned capacity; int* array; }; // Stack Operations struct Stack* createStack( unsigned capacity ) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); if (!stack->array) return NULL; return stack; } int isEmpty(struct Stack* stack) { return stack->top == -1 ; } char peek(struct Stack* stack) { return stack->array[stack->top]; } char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$'; } void push(struct Stack* stack, char op) { stack->array[++stack->top] = op; } // A utility function to check if the given character is operand int isOperand(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } // A utility function to return precedence of a given operator // Higher returned value means higher precedence int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // The main function that converts given infix expression // to postfix expression. int infixToPostfix(char* exp) { int i, k; // Create a stack of capacity equal to expression size struct Stack* stack = createStack(strlen(exp)); if(!stack) // See if stack was created successfully return -1 ; for (i = 0, k = -1; exp[i]; ++i) { // If the scanned character is an operand, add it to output. if (isOperand(exp[i])) exp[++k] = exp[i]; // If the scanned character is an β€˜(β€˜, push it to the stack. else if (exp[i] == '(') push(stack, exp[i]); // If the scanned character is an β€˜)’, pop and output from the stack // until an β€˜(β€˜ is encountered. else if (exp[i] == ')') { while (!isEmpty(stack) && peek(stack) != '(') exp[++k] = pop(stack); if (!isEmpty(stack) && peek(stack) != '(') return -1; // invalid expression else pop(stack); } else // an operator is encountered { while (!isEmpty(stack) && Prec(exp[i]) <= Prec(peek(stack))) exp[++k] = pop(stack); push(stack, exp[i]); } } // pop all the operators from the stack while (!isEmpty(stack)) exp[++k] = pop(stack ); exp[++k] = '\0'; printf( "%sn", exp ); return 0; } // Driver program to test above functions int main() { char exp[] = "a+b*(c^d-e)^(f+g*h)-i"; infixToPostfix(exp); return 0; }