From e44e989515297660f5f8c838ff16e15da4aa6a2f Mon Sep 17 00:00:00 2001 From: Afia Anjum Preety <2apreety@gmail.com> Date: Tue, 13 Oct 2020 11:50:48 +0600 Subject: [PATCH] Adding LinkedList in Java --- LinkedList/Java/2apreety18LinkedList.java | 251 +++++++ .../Graphs/graph/C/Dijkstra_Algorithm.h | 56 ++ .../JavaScript/LinkedListCycleDetection.js | 46 ++ .../Linked_list/C++/Circular Linked List.cpp | 57 ++ .../C++/Doubly Circular Linked List.cpp | 111 ++++ .../Linked_list/C++/Doubly Linked LIst2.cpp | 125 ++++ .../Linked_list/C++/Doubly Linked List.cpp | 93 +++ .../Linked_list/C++/Header Linked List.cpp | 96 +++ .../Linked_list/C++/JosephusProblem.cpp | 59 ++ .../C++/Lavesh_singlyLinkedList.cpp | 143 ++++ .../C++/Linked-list-deleting a node.cpp | 72 ++ .../Linked_list/C++/Linked-list-insertion.cpp | 89 +++ .../Linked_list/C++/MemoryEfficientList.h | 44 ++ .../Linked_list/C++/Merge-Sort-linkedlist.cpp | 143 ++++ .../C++/Quick-sort on linked-list.cpp | 140 ++++ .../C++/SingleLinkedListOperations.cpp | 235 +++++++ .../Linked_list/C++/SinglyLinkedLIst2.cpp | 122 ++++ .../Linked_list/C++/SinglyLinkedList.cpp | 65 ++ .../Linked_list/C++/TemplatedLinkedList.h | 373 +++++++++++ .../Linked_list/C++/add_polynomials.cpp | 146 +++++ .../Linked_list/C++/circular_ll.cpp | 160 +++++ data_structures/Linked_list/C++/cirdll.cpp | 169 +++++ .../C++/delete-linked-list-node.cpp | 89 +++ .../Linked_list/C++/detect_loop.cpp | 67 ++ .../C++/merget_two_sorted_linked_lists.cpp | 27 + .../Linked_list/C++/remove_loop.cpp | 102 +++ .../Linked_list/C++/reverse_linked_list.cpp | 29 + .../C++/templateBasedLinkedList.cpp | 186 ++++++ .../Linked_list/C/DSN_LinkedList_stack.c | 56 ++ data_structures/Linked_list/C/Linked_List.c | 620 ++++++++++++++++++ .../Linked_list/C/circular-linked-list.c | 56 ++ .../Linked_list/C/doubleLinkedList.c | 255 +++++++ .../Linked_list/C/linked_list_complete.c | 143 ++++ .../Linked_list/C/singleLinkedList.c | 206 ++++++ .../Linked_list/Haxe/LinkedList.hx | 155 +++++ .../Linked_list/Haxe/LinkedListTest.hx | 52 ++ .../Python/Doubly Linked List.ipynb | 140 ++++ .../Python/Linked List Traversal.ipynb | 91 +++ .../Python/Simple Linked List.ipynb | 109 +++ .../ZoranPandovski_Singly_linked_list.py | 107 +++ .../ZoranPandovski_Singly_linked_list_test.py | 50 ++ .../Linked_list/Python/cycle_check.py | 42 ++ .../Python/danielcustduran_linked_list.py | 107 +++ .../Linked_list/Python/double_linked_list.py | 71 ++ .../Python/double_linked_list_test.py | 23 + .../Linked_list/Python/linked_list.py | 153 +++++ data_structures/Linked_list/README.md | 18 + data_structures/Linked_list/Read_Me.md | 15 + .../Linked_list/go/DoublyLinkedList.go | 133 ++++ data_structures/Linked_list/go/Linkedlist.go | 102 +++ .../java/CircularlyLinkedList.java | 158 +++++ .../Linked_list/java/Delete_LinkedList.java | 41 ++ .../Linked_list/java/DoublyLinkedList.java | 206 ++++++ .../Linked_list/java/Linked_List.java | 153 +++++ .../Linked_list/java/Linked_List_Test.java | 31 + .../Linked_list/java/reverse_link_list.java | 21 + .../Linked_list/javascript/LList.js | 45 ++ .../javascript/linked_list_insertion.js | 19 + .../javascript/orinayo_linkedlist.js | 181 +++++ .../javascript/orinayo_linkedlist.test.js | 321 +++++++++ .../Linked_list/kotlin/DoublyLinkedList.kt | 164 +++++ .../Linked_list/kotlin/SinglyLinkedList.kt | 103 +++ .../Linked_list/php/LinkedList.php | 104 +++ data_structures/Linked_list/php/Node.php | 28 + data_structures/Linked_list/php/test.php | 43 ++ .../Linked_list/rust/Linked_List.rs | 45 ++ .../Check_is_square/Java/check_is_square.java | 22 + .../Java/ArmstrongNumber.java | 30 + math/isPalindrome/JavaScript/isPalindrome.js | 5 + math/isPalindrome/JavaScript/is_palindrome.js | 1 + math/sieve of eratosthenes/README.md | 15 +- sort/bubble_sort/java/Bubblesort.java | 48 +- sort/counting_sort/Java/CountingSortTest.java | 18 + sort/counting_sort/Java/Counting_sort.java | 61 ++ sort/heap_sort/c++/Heap_Sort.cpp | Bin 1834 -> 1345 bytes sort/selection_sort/c/Selectionsort.c | 86 +-- sort/selection_sort/java/SelectionSort.java | 74 +-- sort/selection_sort/java/Selectionsort.java | 74 +-- stack/C/Array_implementation_stack.c | 55 ++ 79 files changed, 7958 insertions(+), 193 deletions(-) create mode 100644 LinkedList/Java/2apreety18LinkedList.java create mode 100644 data_structures/Graphs/graph/C/Dijkstra_Algorithm.h create mode 100644 data_structures/Linked List Cycle Detection/JavaScript/LinkedListCycleDetection.js create mode 100644 data_structures/Linked_list/C++/Circular Linked List.cpp create mode 100644 data_structures/Linked_list/C++/Doubly Circular Linked List.cpp create mode 100755 data_structures/Linked_list/C++/Doubly Linked LIst2.cpp create mode 100644 data_structures/Linked_list/C++/Doubly Linked List.cpp create mode 100644 data_structures/Linked_list/C++/Header Linked List.cpp create mode 100644 data_structures/Linked_list/C++/JosephusProblem.cpp create mode 100644 data_structures/Linked_list/C++/Lavesh_singlyLinkedList.cpp create mode 100644 data_structures/Linked_list/C++/Linked-list-deleting a node.cpp create mode 100644 data_structures/Linked_list/C++/Linked-list-insertion.cpp create mode 100644 data_structures/Linked_list/C++/MemoryEfficientList.h create mode 100644 data_structures/Linked_list/C++/Merge-Sort-linkedlist.cpp create mode 100644 data_structures/Linked_list/C++/Quick-sort on linked-list.cpp create mode 100644 data_structures/Linked_list/C++/SingleLinkedListOperations.cpp create mode 100755 data_structures/Linked_list/C++/SinglyLinkedLIst2.cpp create mode 100644 data_structures/Linked_list/C++/SinglyLinkedList.cpp create mode 100755 data_structures/Linked_list/C++/TemplatedLinkedList.h create mode 100755 data_structures/Linked_list/C++/add_polynomials.cpp create mode 100644 data_structures/Linked_list/C++/circular_ll.cpp create mode 100644 data_structures/Linked_list/C++/cirdll.cpp create mode 100644 data_structures/Linked_list/C++/delete-linked-list-node.cpp create mode 100644 data_structures/Linked_list/C++/detect_loop.cpp create mode 100644 data_structures/Linked_list/C++/merget_two_sorted_linked_lists.cpp create mode 100644 data_structures/Linked_list/C++/remove_loop.cpp create mode 100644 data_structures/Linked_list/C++/reverse_linked_list.cpp create mode 100644 data_structures/Linked_list/C++/templateBasedLinkedList.cpp create mode 100644 data_structures/Linked_list/C/DSN_LinkedList_stack.c create mode 100644 data_structures/Linked_list/C/Linked_List.c create mode 100644 data_structures/Linked_list/C/circular-linked-list.c create mode 100644 data_structures/Linked_list/C/doubleLinkedList.c create mode 100644 data_structures/Linked_list/C/linked_list_complete.c create mode 100644 data_structures/Linked_list/C/singleLinkedList.c create mode 100644 data_structures/Linked_list/Haxe/LinkedList.hx create mode 100644 data_structures/Linked_list/Haxe/LinkedListTest.hx create mode 100644 data_structures/Linked_list/Python/Doubly Linked List.ipynb create mode 100644 data_structures/Linked_list/Python/Linked List Traversal.ipynb create mode 100644 data_structures/Linked_list/Python/Simple Linked List.ipynb create mode 100644 data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list.py create mode 100644 data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list_test.py create mode 100644 data_structures/Linked_list/Python/cycle_check.py create mode 100644 data_structures/Linked_list/Python/danielcustduran_linked_list.py create mode 100644 data_structures/Linked_list/Python/double_linked_list.py create mode 100644 data_structures/Linked_list/Python/double_linked_list_test.py create mode 100644 data_structures/Linked_list/Python/linked_list.py create mode 100644 data_structures/Linked_list/README.md create mode 100644 data_structures/Linked_list/Read_Me.md create mode 100644 data_structures/Linked_list/go/DoublyLinkedList.go create mode 100644 data_structures/Linked_list/go/Linkedlist.go create mode 100644 data_structures/Linked_list/java/CircularlyLinkedList.java create mode 100644 data_structures/Linked_list/java/Delete_LinkedList.java create mode 100644 data_structures/Linked_list/java/DoublyLinkedList.java create mode 100644 data_structures/Linked_list/java/Linked_List.java create mode 100644 data_structures/Linked_list/java/Linked_List_Test.java create mode 100644 data_structures/Linked_list/java/reverse_link_list.java create mode 100644 data_structures/Linked_list/javascript/LList.js create mode 100644 data_structures/Linked_list/javascript/linked_list_insertion.js create mode 100644 data_structures/Linked_list/javascript/orinayo_linkedlist.js create mode 100644 data_structures/Linked_list/javascript/orinayo_linkedlist.test.js create mode 100644 data_structures/Linked_list/kotlin/DoublyLinkedList.kt create mode 100644 data_structures/Linked_list/kotlin/SinglyLinkedList.kt create mode 100644 data_structures/Linked_list/php/LinkedList.php create mode 100644 data_structures/Linked_list/php/Node.php create mode 100644 data_structures/Linked_list/php/test.php create mode 100644 data_structures/Linked_list/rust/Linked_List.rs create mode 100644 math/Check_is_square/Java/check_is_square.java create mode 100644 math/armstrong_number/Java/ArmstrongNumber.java create mode 100644 math/isPalindrome/JavaScript/isPalindrome.js create mode 100644 math/isPalindrome/JavaScript/is_palindrome.js create mode 100644 sort/counting_sort/Java/CountingSortTest.java create mode 100644 sort/counting_sort/Java/Counting_sort.java create mode 100644 stack/C/Array_implementation_stack.c diff --git a/LinkedList/Java/2apreety18LinkedList.java b/LinkedList/Java/2apreety18LinkedList.java new file mode 100644 index 0000000000..5b6f2c0b2f --- /dev/null +++ b/LinkedList/Java/2apreety18LinkedList.java @@ -0,0 +1,251 @@ +// Java program for reversing the linked list + +public class LinkedList { + + static Node head; + static Node tail; + + static class Node { + + int data; + Node next; + + Node(int d, Node n) { + data = d; + // next = null; + next = n; + + } + } + + //addNode() will add a new node to the list + public static void addNode(int data) { + //Create a new node + Node newNode = new Node(data,null); + + //Checks if the list is empty + if(head == null) { + //If list is empty, both head and tail will point to new node + head = newNode; + tail = newNode; + } + else { + //newNode will be added after tail such that tail's next will point to newNode + tail.next = newNode; + + //newNode will become new tail of the list + tail = newNode; + } + } + + + + /* Function to count the linked list */ + public static int countNode (Node head) { + + int count = 0; + for(Node n = head; n!=null; n=n.next) { + count++; + } + return count; + } + + + /* Function for getting a specific Node from the linked list */ + public static Node nodeAt(int index) { //returns Node + int i = 0; + int size = countNode(head)-1; + + for(Node n = head; n!= null; n=n.next) { + if(index<0 || index >= size) { + return null; + } + if(i == index) { + return n; // n.data for returning the value only + // then change the func to: int nodeAt() + } + i++; + } + + return null; + } + + /* Function for insertion of a Node in the linked list */ + public static Node insert(int element,int index) { + Node newNode = new Node(element,null); + //if head reference changes + if(index == 0) { + newNode.next = head; //changing the ref + head = newNode; //replacing the whole node + }else { + //get the predecessor node first + Node pred = nodeAt(index-1); + newNode.next = pred.next; + pred.next = newNode; + } + return head; + } + + //function will delete a new node to the list + public static Node remove(int index) { + //reference to the remove node + Node removedNode = null; + + //if head ref changes + if(index == 0) { + removedNode = head; + head = head.next; + }else { + //get the predecessor node first + Node pred = nodeAt(index-1); + removedNode = pred.next; + pred.next = removedNode.next; + } + + //helping the GC(garbase collector) + removedNode.data = -100; //null in theo + removedNode.next = null; + + return head; //sending reference head of the updated list + + } + + /* Function for getting value from a specific Node in the linked list */ + public static int nodeAtVal(int index) { //returns Node / getNode() + int i = 0; + int size = countNode(head)-1; + + for(Node n = head; n!= null; n=n.next) { + if(index<0 || index > size) { + return (Integer) null; + } + if(i == index) { + return n.data; // n.data for returning the value only + // then change the func to: int nodeAt() + } + i++; + } + + return (Integer) null; //index out of bounds + } + + + /*Function to set a given value in a Node*/ + public static int set(int value,int index) { + Node node = nodeAt(index); + if(node == null) { + return (Integer) null; + } + else { + int oldElem = node.data; //keeping the old data in a variable + node.data = value; //setting the value + return oldElem; + } + } + + + /*Function for searching the index of a given element/value in a list*/ + public static int indexOf(int value) { + int index = 0; + for(Node n = head; n!= null ; n = n.next) { + if(n.data == value) { + return index; + } + index++; + } + return -1; + } + + /* Function to reverse the linked list */ + public static Node reverseList(Node head) { + + Node revHead = null; + for( Node n = head; n!= null; n = n.next) { + Node newNode = new Node(n.data,null); + //add the node's copy to the beginning of the reversed list + + newNode.next = revHead; + revHead = newNode; + + } + return revHead; + } + + /* Function to copy the linked list */ + public static Node copyList() { + Node copyHead = new Node(head.data, null); + Node copyTail = copyHead; + + for(Node n = head.next; n!= null; n=n.next) { + Node newNode = new Node(n.data,null); + copyTail.next = newNode; + copyTail = newNode; + } + return copyHead; + } + + + // prints content of double linked list + void printList(Node n) // Node n = head is being passed + { + /* while (n != null) { + System.out.print(n.data + " "); + n = n.next; + } */ + + for(; n!= null; n=n.next) { + System.out.print(n.data + " "); + } + } + + public static void main(String[] args) + { + LinkedList list = new LinkedList(); + /*list.head = new Node(85); + list.head.next = new Node(15); + list.head.next.next = new Node(4); + list.head.next.next.next = new Node(20); + + list.head = new Node(85,null); + list.head.next = new Node(15,null); + list.head.next.next = new Node(200,null); + list.head.next.next.next = new Node(20,null); + list.head.next.next.next.next = new Node(60,null); */ + + list.addNode(85); + list.addNode(15); + list.addNode(4); + list.addNode(20); + + + System.out.println("Number of nodes in the Linked list: "+ list.countNode(head)); + list.set(4, 2); + System.out.println("Value is "+list.nodeAtVal(2)); + + + System.out.print("Given Linked list: "); + for(Node n = head; n!= null; n=n.next) { + System.out.print(n.data + " "); + } + + System.out.println(""); + list.insert(90, 0); + System.out.println("After insertion Given Linked list: "); + for(Node n = head; n!= null; n=n.next) { + System.out.print(n.data + " "); + } + + System.out.println(""); + System.out.print("Reversed linked list: "); + list.printList(list.reverseList(head)); + + System.out.println(""); + System.out.println("Index search result "+list.indexOf(20)); + + list.remove(2); + list.printList(list.copyList()); + + + + } +} diff --git a/data_structures/Graphs/graph/C/Dijkstra_Algorithm.h b/data_structures/Graphs/graph/C/Dijkstra_Algorithm.h new file mode 100644 index 0000000000..3af6d8f9b6 --- /dev/null +++ b/data_structures/Graphs/graph/C/Dijkstra_Algorithm.h @@ -0,0 +1,56 @@ +#include +#include +#define N 6 +#define EBAS 0x7FFFFFFF /*32 bit max value */ +void dijkstra(); + +int Graf[N][N] = {{-1,7,4,-1,2,-1}, + {7,-1,3,2,-1,6}, + {4,3,-1,8,1,-1}, + {-1,2,8,-1,10,3}, + {-1,2,8,-1,10,3} + {-1,6,-1,3,-1,-1}}; +int EKM[N]; +char Path[N][N]; +int main(){ + int i; + dijkstra();; + for(i=0;i Graf[ead][j] + EKM[ead]) + EKM[j] = Graf[ead][j] +EKM[ead]; + strcopy(ROTA[j],ROTA[ead]); + /*strcat(ROTA[j],strchr('A'+ead));*/ + ptr = ROTA[j]; + while (*ptr != NULL) { + ++ptr; + } + *ptr = 'A'+ead, + + ek = EBAS; + for (j = 0; j < count; j++) + if ( !ELEALINDI[j]) + if (EKM[j] < ek) { + ek = EKM[j]; ead = j; + } + ELEALINDI[ead] = 1; + +} diff --git a/data_structures/Linked List Cycle Detection/JavaScript/LinkedListCycleDetection.js b/data_structures/Linked List Cycle Detection/JavaScript/LinkedListCycleDetection.js new file mode 100644 index 0000000000..c4f1917cb0 --- /dev/null +++ b/data_structures/Linked List Cycle Detection/JavaScript/LinkedListCycleDetection.js @@ -0,0 +1,46 @@ + +function ListNode(val) { + this.val = val; + this.next = null; +} + + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + if(!head) { + return false; + } + let ptr1 = head; + let ptr2 = head.next; + let isCycle = true; + while(ptr1 && ptr2) { + if(ptr1 === ptr2) { + break; + } + ptr1 = ptr1.next; + ptr2 = ptr2.next ? ptr2.next.next : ptr2.next; + } + if(!ptr1 || !ptr2) { + isCycle = false; + } + return isCycle; +}; + +var run = function() { + let a = new ListNode(1); + let b = new ListNode(2); + let c = new ListNode(3); + let d = new ListNode(4); + let e = new ListNode(5); + + a.next = b; + b.next = c; + c.next = d; + d.next = e; + e.next = b; + + return hasCycle(a); +} \ No newline at end of file diff --git a/data_structures/Linked_list/C++/Circular Linked List.cpp b/data_structures/Linked_list/C++/Circular Linked List.cpp new file mode 100644 index 0000000000..aca5b552b2 --- /dev/null +++ b/data_structures/Linked_list/C++/Circular Linked List.cpp @@ -0,0 +1,57 @@ +#include +#include + +using namespace std; + +int main() +{ + +struct node{ + int info; + node *next; +}*ptr,*head,*start; + +int c=1,data; + +ptr=new node; +ptr->next=NULL; + +start=head=ptr; + +while(c<3 && c>0){ + cout<<"1.Insert\n2.Link List\n"; + cin>>c; + + switch(c){ + case 1: + cout<<"Enter Data\n"; + cin>>data; + + ptr=new node; + ptr->next=start; + ptr->info=data; + + head->next=ptr; + head=ptr; + + break; + + case 2: + ptr=start->next; + + while(ptr!=start && ptr!=NULL){ + cout<info<<"->"; + ptr=ptr->next; + } + cout<<"\n"; + break; + + default: + cout<<"Wrong Choice\nExiting...\n"; + } + +} + +getch(); +return 0; +} \ No newline at end of file diff --git a/data_structures/Linked_list/C++/Doubly Circular Linked List.cpp b/data_structures/Linked_list/C++/Doubly Circular Linked List.cpp new file mode 100644 index 0000000000..7584dc529e --- /dev/null +++ b/data_structures/Linked_list/C++/Doubly Circular Linked List.cpp @@ -0,0 +1,111 @@ +#include +using namespace std; + +struct Node +{ + int data; + struct Node *next; + struct Node *prev; +}; + +void insertEnd(struct Node** start, int value) +{ + + if (*start == NULL) + { + struct Node* new_node = new Node; + new_node->data = value; + new_node->next = new_node->prev = new_node; + *start = new_node; + return; + } + + Node *last = (*start)->prev; + + struct Node* new_node = new Node; + new_node->data = value; + + new_node->next = *start; + + (*start)->prev = new_node; + + new_node->prev = last; + + last->next = new_node; +} + +void insertBegin(struct Node** start, int value) +{ + struct Node *last = (*start)->prev; + + struct Node* new_node = new Node; + new_node->data = value; // Inserting the data + + new_node->next = *start; + new_node->prev = last; + + last->next = (*start)->prev = new_node; + + *start = new_node; +} + +void insertAfter(struct Node** start, int value1, + int value2) +{ + struct Node* new_node = new Node; + new_node->data = value1; // Inserting the data + + struct Node *temp = *start; + while (temp->data != value2) + temp = temp->next; + struct Node *next = temp->next; + + temp->next = new_node; + new_node->prev = temp; + new_node->next = next; + next->prev = new_node; +} + + +void display(struct Node* start) +{ + struct Node *temp = start; + + printf("\nTraversal in forward direction \n"); + while (temp->next != start) + { + printf("%d ", temp->data); + temp = temp->next; + } + printf("%d ", temp->data); + + printf("\nTraversal in reverse direction \n"); + Node *last = start->prev; + temp = last; + while (temp->prev != last) + { + printf("%d ", temp->data); + temp = temp->prev; + } + printf("%d ", temp->data); +} + +int main() +{ + struct Node* start = NULL; + + insertEnd(&start, 5); + + insertBegin(&start, 4); + + insertEnd(&start, 7); + + insertEnd(&start, 8); + + insertAfter(&start, 6, 5); + + printf("Created circular doubly linked list is: "); + display(start); + + return 0; +} diff --git a/data_structures/Linked_list/C++/Doubly Linked LIst2.cpp b/data_structures/Linked_list/C++/Doubly Linked LIst2.cpp new file mode 100755 index 0000000000..15dfa2acb8 --- /dev/null +++ b/data_structures/Linked_list/C++/Doubly Linked LIst2.cpp @@ -0,0 +1,125 @@ +#include "iostream.h" +using namespace std; +struct Node +{ + int data; + Node* prevs; + Node* link; +}; +Node* A; +void insert() +{ + int n,p; + Node* temp=new Node; + cout<<"Enter the number to be inserted:"; + cin>>n; + cout<<"Enter the position:"; + cin>>p; + if(p==1) + { + temp->prevs=NULL; + temp->data=n; + temp->link=A; + A=temp; + return; + } + Node* temp2=new Node; + temp=A; + for (int i=1;ilink; + } + temp2->data=n; + temp2->link=temp->link; + temp2->prevs=temp; + temp->link=temp2; + temp=temp2->link; + if (temp!=NULL) + { + temp->prevs=temp2; + } +} +void delet() +{ + int p; + cout<<"Enter the position to be deleted:"; + cin>>p; + Node* temp=A; + if(p==1) + { + A=temp->link; + temp=NULL; + A->prevs=NULL; + return; + } + for(int i=1;i<=p-1;i++) + { + temp=temp->link; + } + Node* temp2=new Node; + temp2=temp->prevs; + temp2->link=temp->link; + temp=NULL; + if(temp2->link==NULL) + { + return; + } + temp=temp2->link; + temp->prevs=temp2; +} +void display() +{ + Node* temp=new Node; + temp=A; + while(temp!=NULL) + { + cout<<"->"<data; + temp=temp->link; + } + cout<<"\n"; +} +void rev() +{ + Node* temp=A; + Node* pt=new Node; + while(temp!=NULL) + { + if(temp->link==NULL) + { + A=temp; + } + pt=temp->link; + temp->link=temp->prevs; + temp->prevs=pt; + temp=temp->prevs; + } + +} +void main() +{ + A=NULL; + while(1) + { + int ch; + cout<<"Enter your choice:\n1-Insert\n2-Delete\n3-Display\n4-Reverse\n5-Exit\n->"; + cin>>ch; + switch(ch) + { + case 1: + insert(); + break; + case 2: + delet(); + break; + case 3: + display(); + break; + case 4: + rev(); + break; + case 5: + exit(0); + } + } +} + diff --git a/data_structures/Linked_list/C++/Doubly Linked List.cpp b/data_structures/Linked_list/C++/Doubly Linked List.cpp new file mode 100644 index 0000000000..c8d1fdf3ff --- /dev/null +++ b/data_structures/Linked_list/C++/Doubly Linked List.cpp @@ -0,0 +1,93 @@ +#include +#include + +using namespace std; +int main() +{ +struct node{ + int info; + node *left,*right; +}*ptr,*start,*last,*save; + +int c=1,i=0,data,item; +start=last=NULL; + +while(c<4 && c>0){ + cout<<"1.Insert\n2.Deletion\n3.Link List\n"; + cin>>c; + + switch(c){ + case 1: + cout<<"Enter Data\n"; + cin>>data; + + ptr=new node; + ptr->info=data; + ptr->left=last; + ptr->right=NULL; + + if(start==NULL){ + start=last=ptr; + } + + else{ + last->right=ptr; + last=ptr; + } + break; + + case 2: + if(start==NULL){ + cout<<"Underflow\n"; + } + + else{ + cout<<"Enter Item to be Deleted\n"; + cin>>item; + ptr=start; + + while(ptr!=NULL){ + if(ptr->info==item){ + i++; + if(ptr==start){ + start->left=NULL; + start=start->right; + } + + else{ + ptr->left->right=ptr->right; + ptr->right->left=ptr->left; + } + delete ptr; + cout<<"Item Deleted\n"; + } + ptr=ptr->right; + } + + if(i==0){ + cout<<"Item Does not exist\n"; + } + i=0; + } + break; + + case 3: + + ptr=start; + + while(ptr!=NULL){ + cout<info<<"->"; + ptr=ptr->right; + } + cout<<"\n"; + break; + + default: + cout<<"Wrong Choice\nExiting...\n"; + } + +} + +getch(); +return 0; +} diff --git a/data_structures/Linked_list/C++/Header Linked List.cpp b/data_structures/Linked_list/C++/Header Linked List.cpp new file mode 100644 index 0000000000..b09df4d30a --- /dev/null +++ b/data_structures/Linked_list/C++/Header Linked List.cpp @@ -0,0 +1,96 @@ +#include +#include + +using namespace std; + +struct node{ + int info; + node *next; +}*ptr,*head,*start; + + +//Function for creating new node and Inserting data in the node +struct node* insert(struct node* head,int data){ + ptr=new node; + ptr->next=NULL; + ptr->info=data; + + head->next=ptr; + cout<<"Data Inserted\n"; + return ptr; +} + +//Function for searching item in Linked List +int search(struct node* start,int item){ + ptr=start->next; + int f,k; + f=0; + k=0; + while(ptr!=NULL){ + k++; + if(ptr->info==item){ + f++; + cout<<"Item Found at Node: "<next; + } + return f; +} + +//Function for Printing the Linked List +void printLL(struct node* start){ + + ptr=start->next; + + while(ptr!=NULL){ + cout<info<<"->"; + ptr=ptr->next; + } + cout<<"\n"; + +} + +int main(){ + +int c=1,k=0,item,data; + +ptr=new node; +ptr->next=NULL; +start=head=ptr; + +while(c<4 && c>0){ + cout<<"1.Insert\n2.Search Item\n3.Link List\n"; + cin>>c; + + switch(c){ + case 1: + cout<<"Enter Data\n"; + cin>>data; + + head=insert(head,data); + break; + + case 2: + cout<<"Enter Item that you want to find\n"; + cin>>item; + + int f; + f=search(start,item); + if(f==0){ + cout<<"Item Not Found\n"; + } + break; + + case 3: + printLL(start); + break; + + default: + cout<<"Wrong Choice\nExiting...\n"; + } + +} + +getch(); +return 0; +} \ No newline at end of file diff --git a/data_structures/Linked_list/C++/JosephusProblem.cpp b/data_structures/Linked_list/C++/JosephusProblem.cpp new file mode 100644 index 0000000000..d7ce775771 --- /dev/null +++ b/data_structures/Linked_list/C++/JosephusProblem.cpp @@ -0,0 +1,59 @@ +// CPP solution for Josephus Problem using circular linked list + +#include +using namespace std; + +struct Node +{ + int data; + struct Node *next; +}; + +Node *newNode(int data) +{ +Node *temp = new Node; +temp->next = temp; +temp->data = data; +} + +void getJosephusPosition(int m, int n) +{ + Node *head = newNode(1); + Node *prev = head; + for (int i = 2; i <= n; i++) + { + prev->next = newNode(i); + prev = prev->next; + } + prev->next = head; + Node *ptr1 = head, *ptr2 = head; + while (ptr1->next != ptr1) + { + int count = 1; + while (count != m) + { + ptr2 = ptr1; + ptr1 = ptr1->next; + count++; + } + + ptr2->next = ptr1->next; + ptr1 = ptr2->next; + } + + printf ("Last person left standing " + "(Josephus Position) is %d\n ", + ptr1->data); +} + +int main() +{ + int n; + cout<<"Enter no. of men in the circle - "; + cin>>n; + int m = 2; + cout<<"\n\n"; + getJosephusPosition(m, n); + return 0; +} + diff --git a/data_structures/Linked_list/C++/Lavesh_singlyLinkedList.cpp b/data_structures/Linked_list/C++/Lavesh_singlyLinkedList.cpp new file mode 100644 index 0000000000..90f943562b --- /dev/null +++ b/data_structures/Linked_list/C++/Lavesh_singlyLinkedList.cpp @@ -0,0 +1,143 @@ +#include +#include +using namespace std; +struct node +{ + int info; + node * link; +}; +int main() +{ + int n,item; + node *start; + start=NULL; + do + { + cout<<"1.Insert a new node\n2.Delete a node\n3.Find a node with given data\n4.Find middle of Linked List\n5.Insert a node with " + <<"some data before another node\n6.Exit"; + cin>>n; + switch(n) + { + case 1: + { + node *newnode=new node(); + node *ptr; + cout<<"Enter the info of node"; + cin>>item; + newnode.info=item; + newnode.link=NULL; + if(start==NULL) + { + start=newnode; + } + else + { + ptr=start; + while(ptr.link!=NULL) + { + ptr=ptr.link; + } + ptr.link=newnode; + } + break; + } + case 2: + { + int item; + cout<<"Enter the info of the node to be deleted"; + cin>>item; + + } + case 3: + { + cout<<"Enter the data to find"; + cin>>item; + node *ptr,*loc; + ptr=start; + while(ptr!=NULL) + { + if(ptr.info==item) + { + loc=ptr; + break; + } + ptr=ptr.link; + } + if(loc!=NULL) + cout<<"Found at address: "<>x>>y; + node *newnode=new node(); + newnode.info=x; + if(ptr.info==y) + { + newnode.link=ptr; + start=newnode; + } + else + { while(ptr.info!=y) + { + ptr=ptr.link; + } + while(ptr2.link!=ptr) + { + ptr2=ptr2.link; + } + newnode.link=ptr; + ptr2.link=newnode; + } + } + } + } + while(n!=6); + return 0; +} diff --git a/data_structures/Linked_list/C++/Linked-list-deleting a node.cpp b/data_structures/Linked_list/C++/Linked-list-deleting a node.cpp new file mode 100644 index 0000000000..428c605844 --- /dev/null +++ b/data_structures/Linked_list/C++/Linked-list-deleting a node.cpp @@ -0,0 +1,72 @@ + +#include +#include + + +struct Node +{ + int data; + struct Node *next; +}; + + +void push(struct Node** head_ref, int new_data) +{ + struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); + new_node->data = new_data; + new_node->next = (*head_ref); + (*head_ref) = new_node; +} + + +void deleteNode(struct Node **head_ref, int key) +{ + + struct Node* temp = *head_ref, *prev; + + if (temp != NULL && temp->data == key) + { + *head_ref = temp->next; // Changed head + free(temp); // free old head + return; + } + + while (temp != NULL && temp->data != key) + { + prev = temp; + temp = temp->next; + } + + if (temp == NULL) return; + + prev->next = temp->next; + + free(temp); // Free memory +} + +void printList(struct Node *node) +{ + while (node != NULL) + { + printf(" %d ", node->data); + node = node->next; + } +} + +int main() +{ + struct Node* head = NULL; + + push(&head, 7); + push(&head, 1); + push(&head, 3); + push(&head, 2); + + puts("Created Linked List: "); + printList(head); + deleteNode(&head, 1); + puts("\nLinked List after Deletion of 1: "); + printList(head); + return 0; +} + diff --git a/data_structures/Linked_list/C++/Linked-list-insertion.cpp b/data_structures/Linked_list/C++/Linked-list-insertion.cpp new file mode 100644 index 0000000000..7fcd9ec923 --- /dev/null +++ b/data_structures/Linked_list/C++/Linked-list-insertion.cpp @@ -0,0 +1,89 @@ +#include +#include + +struct Node +{ +int data; +struct Node *next; +}; + +void push(struct Node** head_ref, int new_data) +{ + struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); + + new_node->data = new_data; + + new_node->next = (*head_ref); + + (*head_ref) = new_node; +} + +void insertAfter(struct Node* prev_node, int new_data) +{ + if (prev_node == NULL) + { + printf("the given previous node cannot be NULL"); + return; + } + + struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); + + new_node->data = new_data; + + new_node->next = prev_node->next; + + prev_node->next = new_node; +} + +void append(struct Node** head_ref, int new_data) +{ + struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); + + struct Node *last = *head_ref; /* used in step 5*/ + + new_node->data = new_data; + + new_node->next = NULL; + + if (*head_ref == NULL) + { + *head_ref = new_node; + return; + } + + while (last->next != NULL) + last = last->next; + + last->next = new_node; + return; +} + +void printList(struct Node *node) +{ +while (node != NULL) +{ + printf(" %d ", node->data); + node = node->next; +} +} + +int main() +{ +struct Node* head = NULL; + +append(&head, 6); + +push(&head, 7); + +push(&head, 1); + +append(&head, 4); + +insertAfter(head->next, 8); + +printf("\n Created Linked list is: "); +printList(head); + +return 0; +} + diff --git a/data_structures/Linked_list/C++/MemoryEfficientList.h b/data_structures/Linked_list/C++/MemoryEfficientList.h new file mode 100644 index 0000000000..82836d3193 --- /dev/null +++ b/data_structures/Linked_list/C++/MemoryEfficientList.h @@ -0,0 +1,44 @@ +#include +using namespace std; +class XORLinkedList{ +public: + int data; + XORLinkedList* xorPtr; + XORLinkedList(int data){ + this->data=data; + this->xorPtr=NULL; + } +}; +XORLinkedList* XOR(XORLinkedList* prev,XORLinkedList* next){ + return (XORLinkedList*)((unsigned int)(prev) ^(unsigned int)(next)); +} +XORLinkedList* insertAtIthPositionHelper(XORLinkedList** head,int data,int i,XORLinkedList** prev){ + if(*head==NULL){ + if(i==0){ + XORLinkedList* newNode=new XORLinkedList(data); + (*head)=newNode; + } + return (*head); + } + if(i==0){ + XORLinkedList* newNode=new XORLinkedList(data); + (*head)->xorPtr=XOR((*prev),newNode); + newNode->xorPtr=XOR((*prev),NULL); + return newNode; + } + XORLinkedList* temp=XOR((*prev),(*head)); + XORLinkedList* prev2=(*head); + (*head)=insertAtIthPositionHelper(&temp,data,i-1,&prev2); + return (*head); +} +XORLinkedList* insertAtIthPosition(XORLinkedList** head,int data,int i){ + return insertAtIthPositionHelper(head,data,i,NULL); +} +void printList(XORLinkedList* prev,XORLinkedList* head){ + if(head==NULL){ + return; + } + cout<data<<" "; + printList(head,XOR(head->xorPtr,prev)); + return; +} diff --git a/data_structures/Linked_list/C++/Merge-Sort-linkedlist.cpp b/data_structures/Linked_list/C++/Merge-Sort-linkedlist.cpp new file mode 100644 index 0000000000..a0452bdeb8 --- /dev/null +++ b/data_structures/Linked_list/C++/Merge-Sort-linkedlist.cpp @@ -0,0 +1,143 @@ + + +#include +#include + + +struct Node +{ + int data; + struct Node* next; +}; + + +struct Node* SortedMerge(struct Node* a, struct Node* b); +void FrontBackSplit(struct Node* source, + struct Node** frontRef, struct Node** backRef); + + +void MergeSort(struct Node** headRef) +{ +struct Node* head = *headRef; +struct Node* a; +struct Node* b; + + +if ((head == NULL) || (head->next == NULL)) +{ + return; +} + + +FrontBackSplit(head, &a, &b); + + +MergeSort(&a); +MergeSort(&b); + + +*headRef = SortedMerge(a, b); +} + + +struct Node* SortedMerge(struct Node* a, struct Node* b) +{ +struct Node* result = NULL; + +if (a == NULL) + return(b); +else if (b==NULL) + return(a); + + +if (a->data <= b->data) +{ + result = a; + result->next = SortedMerge(a->next, b); +} +else +{ + result = b; + result->next = SortedMerge(a, b->next); +} +return(result); +} + + +void FrontBackSplit(struct Node* source, + struct Node** frontRef, struct Node** backRef) +{ + struct Node* fast; + struct Node* slow; + slow = source; + fast = source->next; + + + while (fast != NULL) + { + fast = fast->next; + if (fast != NULL) + { + slow = slow->next; + fast = fast->next; + } + } + + + *frontRef = source; + *backRef = slow->next; + slow->next = NULL; +} + + +void printList(struct Node *node) +{ +while(node!=NULL) +{ +printf("%d ", node->data); +node = node->next; +} +} + + +void push(struct Node** head_ref, int new_data) +{ + +struct Node* new_node = + (struct Node*) malloc(sizeof(struct Node)); + + +new_node->data = new_data; + + +new_node->next = (*head_ref); + + +(*head_ref) = new_node; +} + + +int main() +{ + +struct Node* res = NULL; +struct Node* a = NULL; + + +push(&a, 15); +push(&a, 10); +push(&a, 5); +push(&a, 20); +push(&a, 3); +push(&a, 2); + + +MergeSort(&a); + +printf("Sorted Linked List is: \n"); +printList(a); + +getchar(); +return 0; +} + diff --git a/data_structures/Linked_list/C++/Quick-sort on linked-list.cpp b/data_structures/Linked_list/C++/Quick-sort on linked-list.cpp new file mode 100644 index 0000000000..62f0fc10e3 --- /dev/null +++ b/data_structures/Linked_list/C++/Quick-sort on linked-list.cpp @@ -0,0 +1,140 @@ +#include +#include +using namespace std; + +struct Node +{ + int data; + struct Node *next; +}; + +void push(struct Node** head_ref, int new_data) +{ + struct Node* new_node = new Node; + + new_node->data = new_data; + + new_node->next = (*head_ref); + + (*head_ref) = new_node; +} + +void printList(struct Node *node) +{ + while (node != NULL) + { + printf("%d ", node->data); + node = node->next; + } + printf("\n"); +} + +struct Node *getTail(struct Node *cur) +{ + while (cur != NULL && cur->next != NULL) + cur = cur->next; + return cur; +} + +struct Node *partition(struct Node *head, struct Node *end, + struct Node **newHead, struct Node **newEnd) +{ + struct Node *pivot = end; + struct Node *prev = NULL, *cur = head, *tail = pivot; + + while (cur != pivot) + { + if (cur->data < pivot->data) + { + + if ((*newHead) == NULL) + (*newHead) = cur; + + prev = cur; + cur = cur->next; + } + else + { + if (prev) + prev->next = cur->next; + struct Node *tmp = cur->next; + cur->next = NULL; + tail->next = cur; + tail = cur; + cur = tmp; + } + } + + + if ((*newHead) == NULL) + (*newHead) = pivot; + + + (*newEnd) = tail; + + + return pivot; +} + + + +struct Node *quickSortRecur(struct Node *head, struct Node *end) +{ + + if (!head || head == end) + return head; + + Node *newHead = NULL, *newEnd = NULL; + + struct Node *pivot = partition(head, end, &newHead, &newEnd); + + + if (newHead != pivot) + { + + struct Node *tmp = newHead; + while (tmp->next != pivot) + tmp = tmp->next; + tmp->next = NULL; + + + newHead = quickSortRecur(newHead, tmp); + + + tmp = getTail(newHead); + tmp->next = pivot; + } + + pivot->next = quickSortRecur(pivot->next, newEnd); + + return newHead; +} + + +void quickSort(struct Node **headRef) +{ + (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); + return; +} + + +int main() +{ + struct Node *a = NULL; + push(&a, 5); + push(&a, 20); + push(&a, 4); + push(&a, 3); + push(&a, 30); + + cout << "Linked List before sorting \n"; + printList(a); + + quickSort(&a); + + cout << "Linked List after sorting \n"; + printList(a); + + return 0; +} + diff --git a/data_structures/Linked_list/C++/SingleLinkedListOperations.cpp b/data_structures/Linked_list/C++/SingleLinkedListOperations.cpp new file mode 100644 index 0000000000..1e6326c596 --- /dev/null +++ b/data_structures/Linked_list/C++/SingleLinkedListOperations.cpp @@ -0,0 +1,235 @@ +#include +#include +using namespace std; + +struct node // Node structure +{ + int data; + struct node *link; +}; +struct node *root=NULL; + + +void append() //Function to append node in the end +{ + struct node *temp; + temp=(struct node *)malloc(sizeof(struct node)); + + cout<<"Enter Node Data"<>temp->data; + temp->link=NULL; + + if(root==NULL) + { + root=temp; + } + else + { + struct node *p; + p=root; + while(p->link!=NULL) + { + p=p->link; + } + p->link=temp; + } +} + + + +void appendatbegin() //Function to append node in the beginning +{ + +struct node *temp; +temp=(struct node*)malloc(sizeof(struct node)); + +cout<<"Enter Node data"<>temp->data; +temp->link=NULL; + +if(root==NULL) +{ + root=temp; +} +else +{ + temp->link=root; + root=temp; +} +} + + +int length() // Function to find length of the list +{ + struct node *temp; + int count=0; + temp=root; + if(temp==NULL) + cout<<"List Empty"<link; + count++; + } + + return count; + } +} + + + +void appendatmiddle() //Function to append a node in the middle +{ + +struct node *temp,*p; +int loc,len; +int i=1; + +cout<<"Enter Location"<>loc; + +len=length(); + +if(loc>len) +{ + cout<<"Invalid Location"<link; + i++; + } + + temp=(struct node *)malloc(sizeof(struct node)); + + cout<<"Enter Node Data"<>temp->data; + temp->link=NULL; + + temp->link=p->link; + p->link=temp; + +} +} + +void display() //Function to display list +{ + struct node *temp; + temp=root; + if(root==NULL) + { + cout<<"List Empty"<data<<"->"; + temp=temp->link; + } + cout<<"NULL"; + } +} + + + + +void deletenode() //Function to delete a node +{ + struct node *temp; + int len,loc; + len=length(); + + cout<<"Enter Location of node to be deleted"<>loc; + + if(loc>len) + { + cout<<"Invalid Location "<link; + temp->link=NULL; + free(temp); +} +else //To delete both the last node and node in the middle +{ +struct node *p, *q; +int i=1; +p=root; +while(ilink; + i++; +} +q=p->link; + +p->link=q->link; +q->link=NULL; +free(q); +} +} + + +void deletelist() //To delete the whole list +{ + struct node *p,*q; + p=root; + while(p!=NULL) + { + q=p->link; + free(p); + p=q; + } + root=NULL; + cout<"List Deleted "<>ch; + switch(ch) + { + case 1: append();break; + case 2: appendatbegin();break; + case 3: appendatmiddle();break; + case 4: l=length(); + cout<<"Length is "<>n; + cout<<"Enter the position:"; + cin>>p; + Node* temp=new Node; + if (p==1) + { + temp->link=A; + temp->data=n; + A=temp; + return; + } + Node* temp2=A; + for(int i=1;ilink; + } + temp->link=temp2->link; + temp2->link=temp; + temp->data=n; +} +void delet() +{ + int p; + cout<<"Enter the position of the element to be deleted:"; + cin>>p; + Node* temp=A; + if (p==1) + { + A=temp->link; + temp=NULL; + return; + } + Node* temp2=new Node; + for(int i=1;ilink; + } + temp2=temp->link; + temp->link=temp2->link; + temp2=NULL; + +} +void display() +{ + Node* temp=A; + while(temp!=NULL) + { + cout<<"->"<data; + temp=temp->link; + } + cout<<"\n"<<"---------------------------"<<"\n"; +} +void count() +{ + int c=0; + Node* temp=A; + while(temp!=NULL) + { + c++; + temp=temp->link; + } + cout<link; + while(prev!=NULL) + { + temp2=prev->link; + prev->link=temp; + temp=prev; + prev=temp2; + } + A->link=NULL; + A=temp; +} +int main() +{ + A=NULL; + while(1) + { + int ch; + cout<<"Enter your choice:\n1-Insert\n2-Delete\n3-Display\n4-Reverse\n5-Count\n6-Exit\n->"; + cin>>ch; + switch(ch) + { + case 1: + insert(); + break; + case 2: + delet(); + break; + case 3: + display(); + break; + case 4: + rev(); + break; + case 5: + count(); + break; + case 6: + exit(0); + } + } +} + diff --git a/data_structures/Linked_list/C++/SinglyLinkedList.cpp b/data_structures/Linked_list/C++/SinglyLinkedList.cpp new file mode 100644 index 0000000000..a20d1555db --- /dev/null +++ b/data_structures/Linked_list/C++/SinglyLinkedList.cpp @@ -0,0 +1,65 @@ +/*A simple C++ program for singly linked list*/ + +#include +using namespace std; +class Node{ +public: + int data; + Node* next; + Node(int value){ + data=value; + next=NULL; + } +}; +Node* takeInput(){ + //size of the linked list + int size; + cin>>size; + + //head and tail of the linked list intialised to NULL + Node* head=NULL; + Node* tail=NULL; + + while(size--){ + //value to be inserted + int num; + cin>>num; + //creation of new node + Node* newNode=new Node(num); + + //if there are no previous elements in the linked list + if(head==NULL) head=tail=newNode; + else{ + //else add the new node to the end of the tail + //and make it tail + tail->next=newNode; + tail=newNode; + } + } + return head; +} +void PrintLL(Node* head){ + + Node* ptr=head; + //transverse until it reaches the end node (NULL) + while(ptr!=NULL){ + cout<data<<" "; + ptr=ptr->next; + } + cout< +#include + +template +class LinkedList +{ + struct Node + { + T data; + Node *next = nullptr, *prev = nullptr; + + //Node() { next = nullptr; prev = nullptr; data = T(); } + }; + + Node *head, *tail; + unsigned int count; + +public: + //=====Accessors=====// + void print() const + { + if (count == 0) + return; + + Node* curr = head; + for (unsigned int i = 0; i < count; i++) + { + std::cout << i + 1 << " " << curr->data << std::endl; + curr = curr->next; + } + } + + void print_matches(T &data) + { + Node *curr = head; + bool found = false; + + for (unsigned int i = 0; i < count; i++) + { + if (curr == nullptr || curr->data == T()) + break; + else if (((std::string)curr->data).find((std::string)(data)) != std::string::npos) + { + std::cout << i + 1 << " " << curr->data << std::endl; + found = true; + } + + curr = curr->next; + } + + if (!found) + std::cout << "not found" << std::endl; + } + + unsigned int size() const + { + return count; + } + + struct Node* at(unsigned int index) + { + if (index >= count) + return nullptr; + + Node* curr = head; + for (unsigned int i = 0; i < count; i++) + { + if (i == index) + return curr; + + curr = curr->next; + } + + return nullptr; + } + + struct Node* get(T &data) + { + if (count == 0) + return nullptr; + + Node* curr; + for (unsigned int i = 0; i < count; i++) + { + curr = this->at(i); + if (curr->data == data) + return curr; + } + + return nullptr; // if reached, list doesn't contain data + } + + bool contains(T &data) + { + if (this->get(data) == nullptr) + return false; + else + return true; + } + + //=====Insertion=====// + void add(T &data) // defaults to end of list + { + Node *temp = new Node(); + temp->data = data; + + if (head == nullptr) + { + temp->next = nullptr; + temp->prev = nullptr; + head = temp; + tail = temp; + } + else if (tail == head) + { + temp->prev = head; + temp->next = nullptr; + head->next = temp; + tail = temp; + } + else + { + temp->prev = tail; + temp->next = nullptr; + tail->next = temp; + tail = temp; + } + + count++; + } + + void add_head(T &data) + { + if (head == nullptr) + add(data); + + else + { + Node *temp = new Node(); + temp->data = data; + temp->next = head; + temp->prev = tail; + head = temp; + count++; + } + } + + void add(T *data, unsigned int size) // defaults to end of list + { + for (unsigned int i = 0; i < size; i++) + add(data[i]); + } + + void insert(unsigned int index, T &data) + { + if (index > count) + return; + else if (index == count || head == nullptr) + add(data); + else if (index == 0) + add_head(data); + else + { + Node *temp = new Node(); + temp->data = data; + temp->next = at(index); + temp->prev = at(index)->prev; + at(index)->prev->next = temp; + at(index)->prev = temp; + count++; + } + } + + void insert(unsigned int index, T *data, unsigned int size) + { + for (unsigned int i = 0; i < size; i++) + { + insert(index, data[i]); + index++; + } + } + + //=====Removal=====// + void pop() // this function exists for quick removal + { + Node *temp = tail->prev; + tail->prev = nullptr; + temp->next = nullptr; + delete tail; + tail = temp; + count--; + } + + void remove_at(unsigned int index) + { + if (index >= count) + return; // throw "Out of bounds"; + else if (head == nullptr) + return; + else if (index == 0) + { + Node *temp = head->next; + head->next = nullptr; + temp->prev = nullptr; + delete head; + head = temp; + } + else if (index == count - 1) + { + Node *temp = tail->prev; + delete tail; + tail = temp; + } + else + { + Node *target = this->at(index); + target->prev->next = target->next; + target->next->prev = target->prev; + target->next = nullptr; + target->prev = nullptr; + delete target; + } + + count--; + + } + + void remove(T &data) + { + if (count == 0) + return; + + Node *target = this->get(data); + if (target == nullptr) + return; + else if (target == head) + { + if (head->next == nullptr) + { + delete head; + head = nullptr; + tail = nullptr; + } + else + { + Node *temp = head->next; + temp->prev = nullptr; + head->next = nullptr; + delete head; + head = temp; + } + } + else if (target == tail) + { + Node *temp = tail->prev; + temp->next = nullptr; + tail->prev = nullptr; + delete tail; + tail = temp; + } + else + { + target->prev->next = target->next; + target->next->prev = target->prev; + target->next = nullptr; + target->prev = nullptr; + delete target; + } + + count--; + } + + void clear() + { + Node *curr = head; + Node *temp; + while (count != 0) + { + temp = curr->next; + delete curr; + curr = temp; + count--; + } + + head = nullptr; + tail = nullptr; + } + + //====Helper Functions====// + void set(const LinkedList &other) + { + this->clear(); + this->count = 0; + + const Node *curr = other.head; + while (curr != nullptr) + { + this->add(curr->data); + curr = curr->next; + } + } + + //=====Operators=====// + const T &operator[](unsigned int index) const + { + if (index > count) + return NULL; // throw "Error!"; + + Node *curr = at(index); + + return curr->data; + } + + T &operator[](unsigned int index) + { + if (index > count) + throw "Error!"; + + Node *curr = at(index); + + return curr->data; + } + + bool operator==(const LinkedList &rhs) const + { + if (this->count != rhs.count) + return false; + + unsigned int matches = 0; + for (unsigned int i = 0; i < count - 1; i++) + { + const Node *curr1 = at(i); + const Node *curr2 = rhs.at(i); + if (curr1->data == curr2->data) + matches++; + } + + if (matches == count - 1) + return true; + else + return false; + } + + LinkedList &operator=(const LinkedList &rhs) + { + set(rhs); + + return *this; + } + + //=====Constructors / Destructor=====// + LinkedList() + { + head = nullptr; + tail = nullptr; + count = 0; + } + + LinkedList(const LinkedList &list) + { + set(list); + } + + ~LinkedList() + { + clear(); + if (head != nullptr) + delete head; + if (tail != nullptr && tail != head) + delete tail; + } +}; diff --git a/data_structures/Linked_list/C++/add_polynomials.cpp b/data_structures/Linked_list/C++/add_polynomials.cpp new file mode 100755 index 0000000000..24ac12978c --- /dev/null +++ b/data_structures/Linked_list/C++/add_polynomials.cpp @@ -0,0 +1,146 @@ +#include +using namespace std; + +class Node +{ +private: + int data; + int pow; + Node *next; + friend class SLL; + +public: + Node(int data, int pow, Node *next = 0) : data(data), pow(pow), next(next) {} +}; + +class SLL +{ +private: + Node *head; + Node *tail; + +public: + SLL() : head(0), tail(0) {} + void insertAtHead(int, int); + void display(); + SLL traverse(SLL &); +}; + +void SLL::insertAtHead(int data, int pow) +{ + Node *node = new Node(data, pow, head); + head = node; + if (!tail) + tail = head; + + return; +} + +void SLL::display() +{ + Node *curr = head; + + while (curr != 0) + { + cout << " " << curr->data << "x^" << curr->pow; + if (curr->next != 0) + cout << " +"; + curr = curr->next; + } + + return; +} + +SLL SLL::traverse(SLL &obj) +{ + Node *currOne = head; + Node *currTwo = obj.head; + SLL polyThree; + + while (currOne != 0 && currTwo != 0) + { + while (currOne != 0 && currTwo != 0 && currOne->pow <= currTwo->pow) + { + if (currOne->pow == currTwo->pow) + { + polyThree.insertAtHead(currOne->data + currTwo->data, currOne->pow); + currTwo = currTwo->next; + } + + else + polyThree.insertAtHead(currOne->data, currOne->pow); + + currOne = currOne->next; + } + + while (currOne != 0 && currTwo != 0 && currOne->pow >= currTwo->pow) + { + if (currOne->pow == currTwo->pow) + { + polyThree.insertAtHead(currOne->data + currTwo->data, currOne->pow); + currOne = currOne->next; + } + else + polyThree.insertAtHead(currTwo->data, currTwo->pow); + + currTwo = currTwo->next; + } + } + + while (currOne != 0) + { + polyThree.insertAtHead(currOne->data, currOne->pow); + currOne = currOne->next; + } + + while (currTwo != 0) + { + polyThree.insertAtHead(currTwo->data, currTwo->pow); + currTwo = currTwo->next; + } + + return polyThree; +} + +int main() +{ + SLL polyOne; + int deg, coeff; + + cout << "\nEnter degree of first polynomial : "; + cin >> deg; + cout << "\npolynomial one : "; + for (int i = deg; i >= 0; i--) + { + cout << "\nEnter " << i << "th degree's coeff : "; + cin >> coeff; + + if (coeff != 0) + polyOne.insertAtHead(coeff, i); + } + + cout << "\npoly one :\n"; + polyOne.display(); + + SLL polyTwo; + + cout << "\nEnter degree of second polynomial : "; + cin >> deg; + cout << "\npolynomial two : "; + + for (int i = deg; i >= 0; i--) + { + cout << "\nEnter " << i << "th degree's coeff : "; + cin >> coeff; + + if (coeff != 0) + polyTwo.insertAtHead(coeff, i); + } + + cout << "\npoly two :\n"; + polyTwo.display(); + + SLL polyThree = polyOne.traverse(polyTwo); + cout << "\npoly three :\n"; + polyThree.display(); +} \ No newline at end of file diff --git a/data_structures/Linked_list/C++/circular_ll.cpp b/data_structures/Linked_list/C++/circular_ll.cpp new file mode 100644 index 0000000000..d51e146ca4 --- /dev/null +++ b/data_structures/Linked_list/C++/circular_ll.cpp @@ -0,0 +1,160 @@ +#include +#include +using namespace std; +struct node +{ + int data; + struct node *next; +}; +struct node *last; +struct node * createNode(int data) +{ + struct node * nnode = (struct node * ) malloc (sizeof(struct node)); + nnode->data = data; + nnode->next = NULL; + return nnode; +} +void addAtBeg(int x) +{ + struct node * nnode = createNode(x); + if(last == NULL) + { + last = nnode; + nnode->next = last; + return; + } + struct node *temp = last->next; + last->next = nnode; + nnode->next = temp; +} +void addAtEnd(int x) +{ + if(last == NULL) + { + return addAtBeg(x); + } + struct node * nnode = createNode(x); + nnode->next = last->next; + last->next = nnode; + last = nnode; +} +void addAfter(int x, int item) +{ + struct node * temp = last->next; + do + { + if(temp->data == item) + { + struct node * nnode = createNode(x); + nnode->next = temp->next; + temp->next = nnode; + if(temp == last) + last = nnode; + return; + } + temp = temp->next; + }while(temp != last->next); + cout<<"Element not found"<next; + if(last == last->next && temp->data == x) + { + struct node *xyz = last; + last = NULL; + delete(xyz); + return; + } + struct node *p = last; + while(p->next != last) + { + if(p->next->data == x) + { + struct node *xyz = p->next; + p->next = xyz->next; + delete(xyz); + return; + } + p = p->next; + } + if(last->data == x) + { + struct node *xyz = last; + p->next = last->next; + last = p; + delete(xyz); + return; + } + cout<<"Element not found"<next; + do + { + cout<data<<" => "; + temp = temp->next; + }while(temp != last->next); + cout<<"NULL"<>n; + switch(n) + { + case 0: + x = 0; + break; + case 1: + cout<<"Enter data to insert: "<>d; + addAtBeg(d); + break; + case 2: + cout<<"Enter data to insert: "<>d; + addAtEnd(d); + break; + case 3: + cout<<"Enter node data to insert after: "<>nd; + cout<<"Enter data to insert: "<>d; + addAfter(d,nd); + break; + case 4: + cout<<"Enter data to delete: "<>d; + del(d); + break; + case 5: + print(); + break; + default: + cout<<"Not a valid case"< + +using namespace std; + + +class node +{ + int info; + node* next; + node* prev; +public: + node* insert(node*); + node* dele(node*); + void display(node*); +}; +node* node::insert(node* start) +{ + int info,ch; + node* cur; + node* temp=new node; + cout<<"Enter information..\n"; + cin>>temp->info; + temp->next=temp; + temp->prev=temp; + cout<<"Enter choice..\n1.Insert at beg\n2.Insert at end\n"; + cin>>ch; + if(ch==2)//Insert at end.. + { + if(start==NULL) + { + cout<<"List empty..\n"; + start = temp; + cout<info; + } + else + { + node* cur; + cur = start; + while(cur->next != start) + cur=cur->next; + cur -> next = temp; + start -> prev = temp; + temp -> next = start; + temp -> prev = cur; + } + + } + else//insert at beg + { + if(start==NULL) + { + cout<<"List empty..\n"; + start = temp; + } + else + { + cur = start; + temp -> next = start; + start -> prev = temp; + while(cur->next != start) + cur = cur->next; + temp -> prev = cur; + cur -> next = temp; + start = temp; + } + } + return start; +} +node* node::dele(node* start) +{ + if(start==NULL) + { + cout<<"List empty..\n"; + return start; + } + else + { + int ele; + cout<<"Enter the element you want to delete..\n"; + cin>>ele; + node* cur = start; + + // Works with a single while loop aswell + // No need to specifically write the cases for first and last elements.. + + if(start->info==ele) + { + cout<<"first element matched..\n"; + (start->prev)->next = start->next; + (start->next)->prev = start->prev; + start = start->next; + delete cur; + return start; + } + while((cur->next != start)) + { + if(cur->info == ele) + { + cout<<"Key matched..\n"; + (cur->prev)->next = cur->next; + (cur->next)->prev = cur->prev; + delete cur; + return start; + } + cur = cur->next; + } + if(cur->info==ele) + { + cout<<"Last element matched..\n"; + (cur->next)->prev = cur->prev; + (cur->prev)->next = cur->next; + delete cur; + return start; + } + else + { + cout<<"Key not matched..\n"; + return start; + } + } +} +void node::display(node* start) +{ + if(start==NULL) + { + cout<<"LIST EMPTY...\n"; + return; + } + if(start == start->next) + { + cout<<"only one element present..\n"; + cout<info<<" "; + return; + } + cout<<"Displaying the list..\n"; + node* cur = start; + while(cur->next != start) + { + cout<<" "<info<<" "; + cur=cur->next; + } + cout<info<<""; +} +int main() +{ + node* start = NULL; + node n; + int ch=1,ch1; + while(ch) + { + cout<<"\n\nEnter 1.insert\n\t2.dele\n\t3.display\n\t4.Exit\n\n"; + cin>>ch1; + switch(ch1) + { + case 1: cout<<"insert..\n"; + start = n.insert(start); + break; + case 2: cout<<"dele..\n"; + start = n.dele(start); + break; + case 3: cout<<"Displaying..\n"; + n.display(start); + break; + case 4: cout<<"Exit..\n"; + ch=0; + break; + } + } +} \ No newline at end of file diff --git a/data_structures/Linked_list/C++/delete-linked-list-node.cpp b/data_structures/Linked_list/C++/delete-linked-list-node.cpp new file mode 100644 index 0000000000..55dae59227 --- /dev/null +++ b/data_structures/Linked_list/C++/delete-linked-list-node.cpp @@ -0,0 +1,89 @@ +// A complete working C program to delete a node in a linked list +// at a given position +#include +#include + +// A linked list node +struct Node +{ + int data; + struct Node *next; +}; + +/* Given a reference (pointer to pointer) to the head of a list +and an int, inserts a new node on the front of the list. */ +void push(struct Node** head_ref, int new_data) +{ + struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); + new_node->data = new_data; + new_node->next = (*head_ref); + (*head_ref) = new_node; +} + +/* Given a reference (pointer to pointer) to the head of a list +and a position, deletes the node at the given position */ +void deleteNode(struct Node **head_ref, int position) +{ +// If linked list is empty +if (*head_ref == NULL) + return; + +// Store head node +struct Node* temp = *head_ref; + + // If head needs to be removed + if (position == 0) + { + *head_ref = temp->next; // Change head + free(temp); // free old head + return; + } + + // Find previous node of the node to be deleted + for (int i=0; temp!=NULL && inext; + + // If position is more than number of ndoes + if (temp == NULL || temp->next == NULL) + return; + + // Node temp->next is the node to be deleted + // Store pointer to the next of node to be deleted + struct Node *next = temp->next->next; + + // Unlink the node from linked list + free(temp->next); // Free memory + + temp->next = next; // Unlink the deleted node from list +} + +// This function prints contents of linked list starting from +// the given node +void printList(struct Node *node) +{ + while (node != NULL) + { + printf(" %d ", node->data); + node = node->next; + } +} + +/* Drier program to test above functions*/ +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 7); + push(&head, 1); + push(&head, 3); + push(&head, 2); + push(&head, 8); + + puts("Created Linked List: "); + printList(head); + deleteNode(&head, 4); + puts("\nLinked List after Deletion at position 4: "); + printList(head); + return 0; +} diff --git a/data_structures/Linked_list/C++/detect_loop.cpp b/data_structures/Linked_list/C++/detect_loop.cpp new file mode 100644 index 0000000000..3e18c99634 --- /dev/null +++ b/data_structures/Linked_list/C++/detect_loop.cpp @@ -0,0 +1,67 @@ +// to check whether there is a loop in a linked list or not. +//using Floyd’s Cycle-Finding Algorithm +#include +using namespace std; + +/* Link list node */ +struct Node +{ + int data; + struct Node* next; +}; + +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = new 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; +} + +// Returns true if there is a loop in linked list +// else returns false. +bool detectLoop(struct Node *h) +{ + if(h==NULL || h->next==NULL) + return false; + Node *slow, *fast; + slow=h; + fast=h->next; + while(fast && fast->next && slow) + { + fast=fast->next->next; + slow=slow->next; + if(slow==fast) + return true; + return false; + } +} + + +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 1); + push(&head, 2); + push(&head, 3); + push(&head, 4); + + /* Create a loop for testing */ + head->next->next->next->next = head; + + if (detectLoop(head)) + cout << "Loop found\n"; + else + cout << "No Loop\n"; + + return 0; +} diff --git a/data_structures/Linked_list/C++/merget_two_sorted_linked_lists.cpp b/data_structures/Linked_list/C++/merget_two_sorted_linked_lists.cpp new file mode 100644 index 0000000000..aaeaf91aa1 --- /dev/null +++ b/data_structures/Linked_list/C++/merget_two_sorted_linked_lists.cpp @@ -0,0 +1,27 @@ + struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; + + +class Solution { +public: + ListNode* reverseList(ListNode* head) { + + ListNode *prev = NULL; + ListNode *cur = head; + ListNode *successor = cur; + + while(cur != NULL) { + + successor = successor->next; + cur->next = prev; + prev = cur; + cur = successor; + + } + + return prev; + } +}; \ No newline at end of file diff --git a/data_structures/Linked_list/C++/remove_loop.cpp b/data_structures/Linked_list/C++/remove_loop.cpp new file mode 100644 index 0000000000..b7ae2e5cd6 --- /dev/null +++ b/data_structures/Linked_list/C++/remove_loop.cpp @@ -0,0 +1,102 @@ +// to remove a loop if there is a loop in the linked list. +//using Floyd’s Cycle-Finding Algorithm +#include +using namespace std; + +struct Node +{ + int key; + struct Node *next; +}; + +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = new Node; + + /* put in the data */ + new_node->key = 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(Node *head) +{ + while (head != NULL) + { + cout << head->key << " "; + head = head->next; + } + cout << endl; +} + +// Function to detect and remove loop in a linked list that may contain loop +void RemoveLoop(struct Node *head) +{ + // If list is empty or has only one node + // without loop + if (head == NULL || head->next == NULL) + return; + + Node *slow ,*fast; + + // Move slow and fast 1 and 2 steps + // ahead respectively. + slow = head; + fast = head->next; + + // Search for loop using slow and + // fast pointers + while (fast && fast->next && slow!=fast) + { + fast = fast->next->next; + slow = slow->next; + } + + /* If loop exists */ + if (slow == fast) + { + slow=head; + if(fast->next==slow) //this handles if there is complete loop. + { + fast->next = NULL; + return; + } + while (slow->next != fast->next) + { + slow = slow->next; + fast = fast->next; + } + + /* since fast->next is the looping point */ + fast->next = NULL; /* remove loop */ + } +} + +/* Driver program to test above function*/ +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 1); + push(&head, 2); + push(&head, 3); + push(&head, 4); + + + /* A loop for testing */ + head->next->next->next->next = head; + + RemoveLoop(head); + + printf("Linked List after removing loop \n"); + printList(head); + + return 0; +} \ No newline at end of file diff --git a/data_structures/Linked_list/C++/reverse_linked_list.cpp b/data_structures/Linked_list/C++/reverse_linked_list.cpp new file mode 100644 index 0000000000..88af9fcd82 --- /dev/null +++ b/data_structures/Linked_list/C++/reverse_linked_list.cpp @@ -0,0 +1,29 @@ + + struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; + + + +class Solution { +public: + ListNode* reverseList(ListNode* head) { + + ListNode *prev = NULL; + ListNode *cur = head; + ListNode *successor = cur; + + while(cur != NULL) { + + successor = successor->next; + cur->next = prev; + prev = cur; + cur = successor; + + } + + return prev; + } +}; \ No newline at end of file diff --git a/data_structures/Linked_list/C++/templateBasedLinkedList.cpp b/data_structures/Linked_list/C++/templateBasedLinkedList.cpp new file mode 100644 index 0000000000..3b0c371155 --- /dev/null +++ b/data_structures/Linked_list/C++/templateBasedLinkedList.cpp @@ -0,0 +1,186 @@ +#include +#include +using namespace std; + +template +class List { + + template + struct Node { + DT data; + Node* next; + + Node() { + data = 0; + next = NULL; + } + }; + + Node
* head; + Node
* current; + int nItems; +public: + List(); + ~List(); + int getNItems() { + return nItems; + } + void insert(const DT& newDataItem); + void insertAt(const DT& newDatItem, int index); + bool isEmpty(); + void display(); + DT getCursor(); + bool gotoNext(); + bool gotoPrior(); + bool moveCursorToEnd(); +}; + +template +List
::List() { + head = NULL; + current = NULL; + nItems = 0; +} + +template +void List
::insert(const DT& newDataItem) { + + if (isEmpty()) { + Node
* newNode = new Node
; + newNode->data = newDataItem; + head = newNode; + + current = head; + + nItems++; + } + else { + Node
* newNode = new Node
; + newNode->data = newDataItem; + newNode->next = NULL; + + current->next = newNode; + current = newNode; + + nItems++; + } +} + +template +bool List
::isEmpty() { + return (head == NULL); +} + +template +void List
::display() { + + Node
* temp = new Node
; + temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + +} + +template +DT List
::getCursor() { + return current->data; +} + +template +bool List
::gotoNext() { + + if (current->next != NULL) { + current = current->next; + return true; + } + + else + return false; +} + +template +bool List
::gotoPrior() { + + // check: not at the beginning + if (current != head) { + + Node
* temp = new Node
; + temp = head; + while (temp->next != current) { + temp = temp->next; + } + current = temp; + + return true; + } + + else + return false; +} + +template +bool List
::moveCursorToEnd() { + + if (head == NULL) + return false; + + Node
* temp = new Node
; + temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + + current = temp; +} + +template +List
::~List() { + Node
* currNode = head; + Node
* nextNode = NULL; + while (currNode != NULL) + { + nextNode = currNode->next; + delete currNode; // destroy the current node + currNode = nextNode; + } +} + +template +void List
::insertAt(const DT& newDataItem, int index) { + + if (index < 0 || index > nItems) { + cout << "Out of Range index!\n"; + moveCursorToEnd(); + return; + } + + if (index == 0) { + Node
* newNode = new Node
; + newNode->data = newDataItem; + newNode->next = head; + head = newNode; + current = newNode; + nItems++; + } + + else { + + int currentIndex = 0; + Node
* temp = head; + while (currentIndex + 1 < index) { + temp = temp->next; + currentIndex++; + } + + + Node
* newNode = new Node
; + newNode->next = temp->next; + temp->next = newNode; + newNode->data = newDataItem; + current = newNode; + nItems++; + } + +} diff --git a/data_structures/Linked_list/C/DSN_LinkedList_stack.c b/data_structures/Linked_list/C/DSN_LinkedList_stack.c new file mode 100644 index 0000000000..534e572f1d --- /dev/null +++ b/data_structures/Linked_list/C/DSN_LinkedList_stack.c @@ -0,0 +1,56 @@ +#include +#include + +struct LinkedList{ + int data; + struct LinkedList* next; +}; + +struct stack *createstack(){ + return NULL; +}; + +void push(struct stack **top, int a){ + struct LinkedList* newnode = (struct LinkedList*)malloc(sizeof(struct LinkedList)); + if(!newnode){ + return NULL; + } + newnode->data=a; + newnode->next=*top; + (*top)=newnode; +} + +int isEmpty(struct stack *top){ + return (top==NULL); +} + +int pop(struct stack **top){ + int data; + struct LinkedList *temp; + if(isEmpty(top)){ + return INT_MIN; + } + temp= *top; + *top= temp->next; + data=temp->data; + free(temp); + return data; +} + +int stacktop(struct stack* top){ + if(isEmpty(top)){ + printf("Empty"); + return INT_MIN; + } + struct LinkedList *t; + t=top; + return ((t)->next->data); +} + +int main(){ + struct stack* A=createstack(); + push(&A,6); + push(&A,2); + stacktop(A); +} + diff --git a/data_structures/Linked_list/C/Linked_List.c b/data_structures/Linked_list/C/Linked_List.c new file mode 100644 index 0000000000..7a38c9ade6 --- /dev/null +++ b/data_structures/Linked_list/C/Linked_List.c @@ -0,0 +1,620 @@ +#include +#include + +typedef struct node +{ + int data; + struct node *next; +}node; + +void printList(node *n) +{ + while(n!=NULL) + { + printf("%d ", n->data); + n = n->next; + } +} + +node* newNode() +{ + node* new_node = (node*)malloc(sizeof(node)); + + return new_node; +} +//To add new node at starting of the list +void push(node** head, int new_data) +{ + + node* new_node = newNode(); + + new_node->data = new_data; + + new_node->next = *head ; + + *head = new_node; + + return; +} + +//insert after a particular position +void insertAfter (node* previous, int new_data) +{ + if(previous==NULL) + return; + + node* new_node = newNode(); + + new_node->data=new_data; + + new_node->next = previous->next; + + previous->next = new_node; + + return ; +} + +//add a new node at the end of the list +void append(node** head, int data) +{ + node* new_node= newNode(); + + new_node->data = data; + + new_node->next = NULL; + + //if the list is empty + if(*head==NULL) + { + *head = new_node; + return; + } + + node* current = *head; + + while(current->next != NULL) + { + current = current->next; + } + + current->next = new_node; + + return ; +} + +//given a key delete a node +void deleteNode (node** head, int key) +{ + node* current=*head, *previous; + + //if the key is in head + if(current!=NULL && current->data==key) + { + *head = current->next; + free(current); + } + + while(current != NULL && current->data != key) + { + previous = current; + current = current->next; + } + + if(current != NULL && current->data==key) + { + previous->next = current->next; + free(current); + } + + + return; +} + +//delete a node at a given position +void deleteNodePosition(node** head, int position) +{ + node* current=*head; + + //if head is to be removed + if(position==0) + { + *head= (*head)->next; // *head=current->next; + free(current); + return; + } + + int i; + + //till the previous node of the node to be deleted + for(i=0; inext; + + if(current==NULL || current->next==NULL) + return; + + node* next=current->next; + + current->next = current->next->next; + + free(next); + + return; +} + +//finding length of linked list +int getCount(node* head) +{ + node *current=head; + + int count=0; + + while(current!=NULL) + { + current=current->next; + count++; + } + + return count; + + /*recursive function will be like + + if(current==NULL) + return 0; + + return 1+getCount(current->next); + + */ + +} + +void deleteFirst(node** head) +{ + /* + 1. Never make head a global pointer it has many disadvantages. + Its value can be changed at any position in the project. + 2.Change the head pointer and then return it. + Its better but it has certain problem if we forget to assign the value to head again. + #head = deleteFirst(node* head) //correct way + #deleteFirst(node* head) //compiler allows it but it is wrong + 3.Send address of the head pointer as an argument + Its considered the best option. + */ + + node* temp=*head; + + *head=(*head)->next; + + free(temp); + + return; + +} + +//swapping two nodes without changing the data field and only changing links +void swapNodes(node** head, int x, int y) +{ + + if(x==y) + return; + + node *prevX=NULL, *currX=*head, *prevY=NULL, *currY=*head; + + while( (currY != NULL && currY->data!=y) || (currX != NULL && currX->data !=x) ) + { + if(currY->data!=y && currY != NULL) + { + prevY=currY; + currY=currY->next; + } + + if(currX->data!=x && currX != NULL) + { + prevX=currX; + currX=currX->next; + } + + } + + if(currX==NULL || currY==NULL) + return; + + if(prevX!=NULL) + prevX->next=currY; + + else + *head=currY; + + if(prevY!=NULL) + prevY->next=currX; + + else + *head=currX; + + node* temp= currY->next; + currY->next=currX->next; + currX->next=temp; + + return; + +} + +//reverse the linked list +void reverse(node** head) +{ + node *previous=NULL, *current=*head, *ahead; + + while(current != NULL) + { + ahead=current->next; + current->next=previous; + previous=current; + current=ahead; + } + + *head=previous; + + return; +} + +//merge two sorted linked list +node* sortedMerge(node* a, node* b) +{ + node* curr1=a, *curr2=b, *head, *result; + + if(a==NULL) + return b; + + else if(b==NULL) + return a; + + if( (a->data) > (b->data) ) + { + head=b; + curr2=curr2->next; + } + else + { + head=a; + curr1=curr1->next; + } + + result=head; + //printf("result=%d", result->data); + + + while(curr1 != NULL && curr2 !=NULL) + { + if( (curr1->data) > (curr2->data) ) + { + result->next = curr2; + curr2=curr2->next; + } + else + { + result->next = curr1; + curr1=curr1->next; + } + result=result->next; + //printf("result=%d", result->data); + } + + if(curr1 == NULL) + result->next=curr2; + else + result->next=curr1; + + return head; + +} + +node* getMiddle(node* head) +{ + node* fast=head, *slow=head; + + if(head != NULL) + { + while(fast!=NULL && fast->next != NULL) + { + fast=fast->next->next; + slow=slow->next; + } + } + + + return slow; +} + + +// Floyd's Cycle finding algorithm +// also known as tortoise and hare algo +int detectLoop(node* head) +{ + node* slow=head, *fast=head; + + while(fast!=NULL && fast->next != NULL) + { + + fast=fast->next->next; + slow=slow->next; + + if(fast==slow) + return 1; + } + + return 0; +} + +// the list is already sorted and inserting a value in it in sorted way +void sortedInsert(node** head, int value) +{ + + node* temp = newNode(); + + temp->data=value; + + + if(*head==NULL || (*head)->data>value ) + { + temp->next=*head; + *head=temp; + return ; + } + + node* current=*head, *previous=*head; + + + while(current!=NULL && value>current->data ) + { + previous=current; + current=current->next; + } + + previous->next=temp; + temp->next=current; + + return ; + +} + +void pairWiseSwap(node* head) +{ + + node* previous=head, *current=head->next; + int temp; + + while(previous!=NULL && current!=NULL) + { + temp=previous->data; + previous->data=current->data; + current->data=temp; + + previous=current->next; + current=previous->next; + } + + return; + + + +} + + +node* sortedIntersect(node* head1, node* head2) +{ + + node* curr1=head1, *curr2=head2; + node* head=NULL; + while(curr1 != NULL && curr2 != NULL) + { + + + if(curr1->data==curr2->data) + { + append(&head, curr1->data); + curr1=curr1->next; + curr2=curr2->next; + } + + else if(curr1->data > curr2->data) + { + curr2=curr2->next; + } + else + { + curr1=curr1->next; + } + } + return head; + +} +struct node *reverseparticular (struct node *head, int k) + +{ + struct node* current=head; + + struct node* prev=NULL; + struct node* after=NULL; + //it will reverse the linked list to every key nodes entered by the users + int x=1; + + while(current!=NULL&&x<=k) + + { + after=current->next; + + current->next=prev; + + prev=current; + + current=after; + + x++; + + } + +if(after!=NULL) + + head->next=reverse(after,k); + + + return prev; + + + +} +//add two list// +struct Node* addTwoLists (struct Node* first, struct Node* second) +{ + struct Node* res = NULL; // res is head node of the resultant list + struct Node *temp, *prev = NULL; + int carry = 0, sum; + + while (first != NULL || second != NULL) //while both lists exist + { + // Calculate value of next digit in resultant list. + // The next digit is sum of following things + // (i) Carry + // (ii) Next digit of first list (if there is a next digit) + // (ii) Next digit of second list (if there is a next digit) + sum = carry + (first? first->data: 0) + (second? second->data: 0); + + // update carry for next calulation + carry = (sum >= 10)? 1 : 0; + + // update sum if it is greater than 10 + sum = sum % 10; + + // Create a new node with sum as data + temp = newNode(sum); + + // if this is the first node then set it as head of the resultant list + if(res == NULL) + res = temp; + else // If this is not the first node then connect it to the rest. + prev->next = temp; + + // Set prev for next insertion + prev = temp; + + // Move first and second pointers to next nodes + if (first) first = first->next; + if (second) second = second->next; + } + + if (carry > 0) + temp->next = newNode(carry); + + // return head of the resultant list + return res; +} +int detectAndRemoveLoop(struct Node *list) +{ + struct Node *slow_p = list, *fast_p = list; + + while (slow_p && fast_p && fast_p->next) + { + slow_p = slow_p->next; + fast_p = fast_p->next->next; + + /* If slow_p and fast_p meet at some point then there + is a loop */ + if (slow_p == fast_p) + { + removeLoop(slow_p, list); + + /* Return 1 to indicate that loop is found */ + return 1; + } + } + + /* Return 0 to indeciate that ther is no loop*/ + return 0; +} + +/* Function to remove loop. + loop_node --> Pointer to one of the loop nodes + head --> Pointer to the start node of the linked list */ +void removeLoop(struct Node *loop_node, struct Node *head) +{ + struct Node *ptr1; + struct Node *ptr2; + + /* Set a pointer to the beging of the Linked List and + move it one by one to find the first node which is + part of the Linked List */ + ptr1 = head; + while (1) + { + /* Now start a pointer from loop_node and check if it ever + reaches ptr2 */ + ptr2 = loop_node; + while (ptr2->next != loop_node && ptr2->next != ptr1) + ptr2 = ptr2->next; + + /* If ptr2 reahced ptr1 then there is a loop. So break the + loop */ + if (ptr2->next == ptr1) + break; + + /* If ptr2 did't reach ptr1 then try the next node after ptr1 */ + ptr1 = ptr1->next; + } + + /* After the end of loop ptr2 is the last node of the loop. So + make next of ptr2 as NULL */ + ptr2->next = NULL; +} +//to rotate a linked list after the given integral position +void rotate(struct node* head_ref,int k) +{ +struct node* temp=*head_ref; +if(k==0) +return; +int count=1; +while(countnext!=NULL) +{ +temp=temp->next; +count++; +} +if(temp=NULL) +return; +struct node* temp2=temp; +while(temp!=NULL) +{ +temp=temp->next; +} +temp->next=(*head_ref); +(*head_ref)=temp2->next; +temp2->next=NULL; + +} +int main() +{ + struct node* a = NULL; + struct node* b = NULL; + struct node *intersect = NULL; + + /* Let us create the first sorted linked list to test the functions + Created linked list will be 1->2->3->4->5->6 */ + push(&a, 6); + push(&a, 5); + push(&a, 4); + push(&a, 3); + push(&a, 2); + push(&a, 1); + + /* Let us create the second sorted linked list + Created linked list will be 2->4->6->8 */ + push(&b, 8); + push(&b, 6); + push(&b, 4); + push(&b, 2); + + /* Find the intersection two linked lists */ + intersect = sortedIntersect(a, b); + + printf("\n Linked list containing common items of a & b \n "); + printList(intersect); + + return 0; +} diff --git a/data_structures/Linked_list/C/circular-linked-list.c b/data_structures/Linked_list/C/circular-linked-list.c new file mode 100644 index 0000000000..e2d0133dc2 --- /dev/null +++ b/data_structures/Linked_list/C/circular-linked-list.c @@ -0,0 +1,56 @@ +#include +#include + +struct Node +{ + int data; + struct Node *next; +}; + +void add(struct Node **head_ref, int data) +{ + struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); + struct Node *temp = *head_ref; + ptr1->data = data; + ptr1->next = *head_ref; + + if (*head_ref != NULL) + { + while (temp->next != *head_ref) + temp = temp->next; + temp->next = ptr1; + } + else + ptr1->next = ptr1; + + *head_ref = ptr1; +} + +void printList(struct Node *head) +{ + struct Node *temp = head; + if (head != NULL) + { + do + { + printf("%d ", temp->data); + temp = temp->next; + } + while (temp != head); + } +} + +int main() +{ + struct Node *head = NULL; + + add(&head, 12); + add(&head, 56); + add(&head, 2); + add(&head, 11); + + printf("Data of Circular Linked List:\n "); + printList(head); + + return 0; +} \ No newline at end of file diff --git a/data_structures/Linked_list/C/doubleLinkedList.c b/data_structures/Linked_list/C/doubleLinkedList.c new file mode 100644 index 0000000000..103d739ca2 --- /dev/null +++ b/data_structures/Linked_list/C/doubleLinkedList.c @@ -0,0 +1,255 @@ +#include +#include + +struct node { + int data; + struct node *prev; + struct node *next; +}; + +struct node * +new_node(int n) { + struct node *elem; + + if ((elem = malloc(sizeof(struct node))) == NULL) { + fprintf(stderr, "Malloc error in %s (%d)", __FILE__, __LINE__); + return NULL; + } + + elem->data = n; + elem->prev = NULL; + elem->next = NULL; + + return elem; +} + +int +add_as_head(struct node **list, int n) { + struct node *head = new_node(n); + + if (head == NULL) + return 0; + + if (*list == NULL) { + *list = head; + return 1; + } + + (*list)->prev = head; + head->next = *list; + *list = head; + + return 1; +} + +int +add_as_tail(struct node **list, int n) { + struct node *new_tail = new_node(n); + struct node *tmp = *list; + + if (new_tail == NULL) + return 0; + + if (*list == NULL) { + *list = new_tail; + return 1; + } + + for (tmp = *list; tmp->next != NULL; tmp = tmp->next); + + tmp->next = new_tail; + new_tail->prev = tmp; + + return 1; +} + +int +free_node(struct node *node) { + if (node == NULL) { + fprintf(stderr, "Illegal free attempt : node is NULL\n"); + return 0; + } + + free(node); + node = NULL; + + return 1; +} + +int +delete_head(struct node **list) { + struct node *old_head = *list; + + if (*list == NULL) + return 0; + + *list = (*list)->next; + (*list)->prev = NULL; + + return free_node(old_head); +} + +int +delete_node(struct node *node) { + if (node == NULL) + return 0; + + if (node->prev != NULL) + node->prev->next = node->next; + if (node->next != NULL) + node->next->prev = node->prev; + + return free_node(node); +} + +int +delete_node_by_value(struct node **list, int n) { + struct node *tmp = NULL; + + if ((*list)->data == n) { + return delete_head(list); + } + + for (tmp = *list; tmp != NULL && tmp->data != n; tmp = tmp->next); + + if (tmp == NULL) + return 0; + + if (tmp->prev != NULL) + tmp->prev->next = tmp->next; + if (tmp->next != NULL) + tmp->next->prev = tmp->prev; + + return free_node(tmp); +} + +int +delete_tail(struct node **list) { + struct node *new_tail = NULL; + struct node *old_tail = NULL; + + for (new_tail = *list; new_tail->next != NULL && new_tail->next->next != NULL; new_tail = new_tail->next); + + old_tail = new_tail->next; + new_tail->next = NULL; + + return free_node(old_tail); +} + +int +free_list(struct node **list) { + struct node *tmp; + + if (*list == NULL) { + fprintf(stderr, "Illegal free attempt : list is NULL\n"); + return 0; + } + + do { + tmp = (*list)->next; + free_node(*list); + *list = tmp; + } while (tmp != NULL); + + return 1; +} + +void +disp_list(struct node *list) { + struct node *tail = NULL; + + printf("Head to tail:\n"); + for (; list != NULL; list = list->next) { + printf("%d", list->data); + if (list->next != NULL) + printf(" <-> "); + else + tail = list; + } + printf("\n"); + + printf("Tail to head:\n"); + for (; tail != NULL; tail = tail->prev) { + printf("%d", tail->data); + if (tail->prev != NULL) + printf(" <-> "); + } + printf("\n"); +} + +//quick sort for double linked list// +Node* partition(Node *l, Node *h) +{ + // set pivot as h element + int x = h->data; + + // similar to i = l-1 for array implementation + Node *i = l->prev; + + // Similar to "for (int j = l; j <= h- 1; j++)" + for (Node *j = l; j != h; j = j->next) + { + if (j->data <= x) + { + // Similar to i++ for array + i = (i == NULL)? l : i->next; + + swap(&(i->data), &(j->data)); + } + } + i = (i == NULL)? l : i->next; // Similar to i++ + swap(&(i->data), &(h->data)); + return i; +} + +/* A recursive implementation of quicksort for linked list */ +void _quickSort(struct Node* l, struct Node *h) +{ + if (h != NULL && l != h && l != h->next) + { + struct Node *p = partition(l, h); + _quickSort(l, p->prev); + _quickSort(p->next, h); + } +} + +// The main function to sort a linked list. It mainly calls _quickSort() +void quickSort(struct Node *head) +{ + // Find last node + struct Node *h = lastNode(head); + + // Call the recursive QuickSort + _quickSort(head, h); +} + +int +main(int argc, char *argv[]) { + struct node *list; + int i; + + /* 4 <-> 3 <-> 2 <-> 1 <-> 0 */ + for (i = 0; i < 5; i++) + add_as_head(&list, i); + + /* 4 <-> 3 <-> 2 <-> 1 <-> 0 <-> 99 */ + add_as_tail(&list, 99); + + /* 4 <-> 3 <-> 2 <-> 1 <-> 0 */ + delete_node_by_value(&list, 99); + + /* 3 <-> 2 <-> 1 <-> 0 */ + delete_head(&list); + + /* 3 <-> 1 <-> 0 */ + delete_node(list->next); + + /* 3 <-> 1 */ + delete_tail(&list); + + disp_list(list); + + free_list(&list); + + return EXIT_SUCCESS; +} diff --git a/data_structures/Linked_list/C/linked_list_complete.c b/data_structures/Linked_list/C/linked_list_complete.c new file mode 100644 index 0000000000..c835628a35 --- /dev/null +++ b/data_structures/Linked_list/C/linked_list_complete.c @@ -0,0 +1,143 @@ +#include +#include +struct node{ + int data; + struct node *link; +}*headptr = NULL; +void insert(int num,int pos){ + struct node *newptr,*temp,*prev; + newptr = (struct node*)malloc(sizeof(struct node)); + newptr->data = num; + if(headptr==NULL){ + headptr = newptr; + newptr->link = NULL; + } + else if(pos==0){ + temp = headptr; + headptr = newptr; + newptr->link = temp; + } + else{ + int i; + prev = headptr; + for(i=0;i<=pos-2;i++) + prev = prev->link; + temp = prev->link; + prev->link = newptr; + newptr->link = temp; + } +} +void insertLast(int num){ + struct node* newptr = (struct node*)malloc(sizeof(struct node)); + newptr->data = num; + struct node* temp = headptr; + while(temp->link!=NULL) + temp = temp->link; + temp->link = newptr; + newptr->link = NULL; + +} +void delete(int pos){ + struct node *prev,*curr; + int i; + if(headptr==NULL) + printf("List Empty!\n"); + else{ + prev = headptr; + if(pos==0){ + curr = headptr; + headptr = headptr->link; + free(curr); + } + else{ + for(i=0;i<=pos-2;i++) + prev = prev->link; + curr = prev->link; + if(curr->link!=NULL) + prev->link = curr->link; + else + prev->link = NULL; + } + } +} +void delete_last(){ + struct node* temp = headptr; + while(temp->link->link!=NULL) + temp = temp->link; + temp->link = NULL; +} +void display(){ + struct node* prev = NULL, *curr = headptr, *next = NULL,*temp; + while(curr!=NULL){ + next = curr->link; + curr->link = prev; + prev = curr; + curr = next; + } + temp = prev; + while(temp!=NULL){ + printf("%d ",temp->data); + temp = temp->link; + } + printf("\n"); +} +// void display2(struct node* curr){ +// if(curr->link!=NULL) +// display2(curr->link); +// printf("%d ",curr->data); +// } +void reverse(struct node* temp){ + if(temp->link != NULL) + reverse(temp->link); + if(temp != headptr) + printf("%d->", temp->data); + else + printf("%d", temp->data); +} + +void display3(struct node* curr){ + if(curr != NULL){ + printf("%d ",curr->data); + display3(curr->link); + } +} +int main(){ + int t=0,ch,num,pos; + struct node* curr = headptr; + + while(t==0){ + printf("Choice: "); + scanf("%d",&ch); + switch(ch){ + case 1: + printf("Num and pos: "); + scanf("%d%d",&num,&pos); + insert(num,pos); + break; + case 2: + //printf("Function to delete....\n"); + printf("Pos: "); + scanf("%d",&pos); + delete(pos); + break; + case 3: + reverse(headptr); + printf("\n"); + break; + case 4: + t = 1; + break; + case 5: + printf("Last node: "); + scanf("%d",&num); + insertLast(num); + break; + case 6: + delete_last(); + break; + default: + printf("Error choice!\n"); + break; + } + } +} diff --git a/data_structures/Linked_list/C/singleLinkedList.c b/data_structures/Linked_list/C/singleLinkedList.c new file mode 100644 index 0000000000..f9a8943aca --- /dev/null +++ b/data_structures/Linked_list/C/singleLinkedList.c @@ -0,0 +1,206 @@ +#include +#include + +struct node { + int data; + struct node *next; +}; + +struct node * +new_node(int n) { + struct node *elem; + + if ((elem = malloc(sizeof(struct node))) == NULL) { + fprintf(stderr, "Malloc error in %s (%d)", __FILE__, __LINE__); + return NULL; + } + + elem->data = n; + elem->next = NULL; + + return elem; +} + +int +add_as_head(struct node **list, int n) { + struct node *head = new_node(n); + + if (head == NULL) + return 0; + + if (*list == NULL) { + *list = head; + return 1; + } + + head->next = *list; + *list = head; + + return 1; +} + +int +add_as_tail(struct node **list, int n) { + struct node *tail = new_node(n); + struct node *tmp = *list; + + if (tail == NULL) + return 0; + + if (*list == NULL) { + *list = tail; + return 1; + } + + for (tmp = *list; tmp->next != NULL; tmp = tmp->next); + + tmp->next = tail; + + return 1; +} + +int +free_node(struct node *node) { + if (node == NULL) { + fprintf(stderr, "Illegal free attempt : node is NULL\n"); + return 0; + } + + free(node); + node = NULL; + + return 1; +} + +int +delete_head(struct node **list) { + struct node *old_head = *list; + + if (*list == NULL) + return 0; + + *list = (*list)->next; + return free_node(old_head); +} + +int +delete_node(struct node **list, int n) { + struct node *tmp = NULL; + struct node *node_to_delete = NULL; + + if ((*list)->data == n) { + return delete_head(list); + } + + for (tmp = *list; tmp->next != NULL && tmp->next->data != n; tmp = tmp->next); + + if (tmp->next == NULL) + return 0; + + node_to_delete = tmp->next; + tmp->next = node_to_delete->next; + + return free_node(node_to_delete); +} + +int +delete_tail(struct node **list) { + struct node *new_tail = NULL; + struct node *old_tail = NULL; + + for (new_tail = *list; new_tail->next != NULL && new_tail->next->next != NULL; new_tail = new_tail->next); + + old_tail = new_tail->next; + new_tail->next = NULL; + + return free_node(old_tail); +} + +int +free_list(struct node **list) { + struct node *tmp; + + if (*list == NULL) { + fprintf(stderr, "Illegal free attempt : list is NULL\n"); + return 0; + } + + do { + tmp = (*list)->next; + free_node(*list); + *list = tmp; + } while (tmp != NULL); + + return 1; +} + +void +disp_list(struct node *list) { + for (; list != NULL; list = list->next) { + printf("%d", list->data); + if (list->next != NULL) + printf(" -> "); + } + printf("\n"); +} +//this is the optimized nethod for detection of loop in the linked list// +void detectanddelete(struct node* head_ref) +{ + if(head_ref==NULL||head_ref->next==NULL) + return; + struct node* fast=head_ref; + struct node* slow=head_ref; + slow=slow->next; + fast=fast->next->next; + while(fast&&fast->next) + { + if(slow==fast) + break; + slow=slow->next; + fast=fast->next->next; + } + if(slow==fast) + { + slow=head_ref; + while(slow->next!=fast->next) + { + slow=slow->next; + fast=fast->next; + } + fast->next=NULL; + } + + + +}; + +int +main(int argc, char *argv[]) { + struct node *list; + int i; + + /* 4 -> 3 -> 2 -> 1 -> 0 */ + for (i = 0; i < 5; i++) + add_as_head(&list, i); + + /* 4 -> 3 -> 2 -> 1 -> 0 -> 99 */ + add_as_tail(&list, 99); + + /* 4 -> 3 -> 2 -> 1 -> 0 */ + delete_node(&list, 99); + + /* 3 -> 2 -> 1 -> 0 */ + delete_head(&list); + + /* 3 -> 1 -> 0 */ + delete_node(&list, 2); + + /* 3 -> 1 */ + delete_tail(&list); + + disp_list(list); + + free_list(&list); + + return EXIT_SUCCESS; +} diff --git a/data_structures/Linked_list/Haxe/LinkedList.hx b/data_structures/Linked_list/Haxe/LinkedList.hx new file mode 100644 index 0000000000..e3e82fd1c1 --- /dev/null +++ b/data_structures/Linked_list/Haxe/LinkedList.hx @@ -0,0 +1,155 @@ +class LinkedList { + + /** + * The length of `this` list. + */ + public var length(default, null):Int; + + /** + * The first item in the list or null + */ + public var first(get, never):Null; + inline function get_first():Null { + return head == null ? null : head.item; + } + + /** + * The last item in the list or null + */ + public var last(get, never):Null; + inline function get_last():Null { + return tail == null ? null : tail.item; + } + + var head:ListNode; + var tail:ListNode; + + public function new() { + length = 0; + } + + /** + * Adds given item to the end of the list + * @param item + * @return T + */ + public function append(item:T):T { + var n = new ListNode(item, null); + if(head == null) head = n; + else tail.next = n; + + tail = n; + length++; + + return item; + } + + /** + * Adds given item to the beginning of the list + * @param item + * @return T + */ + public function prepend(item:T):T { + var n = new ListNode(item, head); + head = n; + if(tail == null) tail = n; + length++; + + return item; + } + + /** + * Checks if list has no items + * @return Bool + */ + public inline function isEmpty():Bool { + return length == 0; + } + + /** + * Clears the list + */ + public inline function clear() { + head = tail = null; + length = 0; + } + + /** + * Gets item at given index or null + * @param index + * @return Null + */ + public function getItemAt(index:Int):Null { + var curr = head; + var cntr = 0; + while (curr != null) { + if(cntr++ == index) return curr.item; + else curr = curr.next; + } + return null; + } + + /** + * Removes given item from the list and returns true if it was successfully removed + * @param item + * @return Bool + */ + public function remove(item:T):Bool { + var curr = head; + var prev:ListNode = null; + while(curr != null) { + if(curr.item == item) { + if(prev == null) head = curr.next; + else prev.next = curr.next; + + if(tail == curr) tail = prev; + length--; + return true; + } + prev = curr; + curr = curr.next; + } + return false; + } + + /** + * Removes the first item from the list and returns that item. + * @return Null + */ + public function shift():Null { + if(head == null) return null; + + var item = head.item; + head = head.next; + + if(head == null) tail = null; + + length--; + return item; + } + + /** + * Calls `fn` for each item of the list. + * @param fn function with two arguments, where first arg is an item, second is an index of the item + */ + public function iterate(fn:T->Int->Void) { + var curr = head; + var i = 0; + while(curr != null) { + fn(curr.item, i++); + curr = curr.next; + } + } + +} + +private class ListNode { + + public var item:T; + public var next:ListNode; + + public function new(item:T, next:ListNode){ + this.item = item; + this.next = next; + } +} \ No newline at end of file diff --git a/data_structures/Linked_list/Haxe/LinkedListTest.hx b/data_structures/Linked_list/Haxe/LinkedListTest.hx new file mode 100644 index 0000000000..a39e02a3f8 --- /dev/null +++ b/data_structures/Linked_list/Haxe/LinkedListTest.hx @@ -0,0 +1,52 @@ +package; + +class LinkedListTest { + static function main() { + + var list = new LinkedList(); + + trace(list.length == 0); + trace(list.isEmpty()); + trace(list.first == null); + trace(list.last == null); + + list.append('world'); + list.prepend('my'); + list.prepend('hello'); + + trace(list.length == 3); + trace(!list.isEmpty()); + trace(list.first == 'hello'); + trace(list.last == 'world'); + trace(list.getItemAt(1) == 'my'); + trace(list.remove('my')); + trace(!list.remove('not my')); + trace(list.length == 2); + trace(list.remove('hello')); + trace(list.remove('world')); + trace(list.length == 0); + + list.append('world'); + list.prepend('hello'); + + trace(list.getItemAt(0), list.getItemAt(1)); + list.clear(); + trace(list.isEmpty()); + + list.append('hello'); + list.append('world'); + trace(list.shift() == 'hello'); + trace(list.shift() == 'world'); + trace(list.first == null, list.last == null); + + var list = new LinkedList(); + list.append({prop: 'foo'}); + list.append({prop: 'bar'}); + list.iterate(function(item, ind) { item.prop = item.prop.toUpperCase(); }); + trace(list.getItemAt(0).prop == 'FOO', list.getItemAt(1).prop == 'BAR'); + } +} + +typedef SomeStruct = { + var prop:String; +} diff --git a/data_structures/Linked_list/Python/Doubly Linked List.ipynb b/data_structures/Linked_list/Python/Doubly Linked List.ipynb new file mode 100644 index 0000000000..3be7ea1fce --- /dev/null +++ b/data_structures/Linked_list/Python/Doubly Linked List.ipynb @@ -0,0 +1,140 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Node of a doubly linked list \n", + "class Node: \n", + "\tdef __init__(self, next=None, prev=None, data=None): \n", + "\t\tself.next = next # reference to next node in DLL \n", + "\t\tself.prev = prev # reference to previous node in DLL \n", + "\t\tself.data = data \n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# Adding a node at the front of the list \n", + "def push(self, new_data): \n", + "\n", + "\t# 1 & 2: Allocate the Node & Put in the data \n", + "\tnew_node = Node(data = new_data) \n", + "\n", + "\t# 3. Make next of new node as head and previous as NULL \n", + "\tnew_node.next = self.head \n", + "\tnew_node.prev = None\n", + "\n", + "\t# 4. change prev of head node to new node \n", + "\tif self.head is not None: \n", + "\t\tself.head.prev = new_node \n", + "\n", + "\t# 5. move the head to point to the new node \n", + "\tself.head = new_node \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# Given a node as prev_node, insert \n", + "# a new node after the given node \n", + "\n", + "def insertAfter(self, prev_node, new_data): \n", + "\n", + "\t\t# 1. check if the given prev_node is NULL \n", + "\t\tif prev_node is None: \n", + "\t\t\tprint(\"This node doesn't exist in DLL\") \n", + "\t\t\treturn\n", + "\n", + "\t\t#2. allocate node & 3. put in the data \n", + "\t\tnew_node = Node(data = new_data) \n", + "\n", + "\t\t# 4. Make next of new node as next of prev_node \n", + "\t\tnew_node.next = prev_node.next\n", + "\n", + "\t\t# 5. Make the next of prev_node as new_node \n", + "\t\tprev_node.next = new_node \n", + "\n", + "\t\t# 6. Make prev_node as previous of new_node \n", + "\t\tnew_node.prev = prev_node \n", + "\n", + "\t\t# 7. Change previous of new_node's next node */ \n", + "\t\tif new_node.next is not None: \n", + "\t\t\tnew_node.next.prev = new_node \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "# Add a node at the end of the DLL \n", + "def append(self, new_data): \n", + "\n", + "\t\t# 1. allocate node 2. put in the data \n", + "\t\tnew_node = Node(data = new_data) \n", + "\t\tlast = self.head \n", + "\n", + "\t\t# 3. This new node is going to be the \n", + "\t\t# last node, so make next of it as NULL \n", + "\t\tnew_node.next = None\n", + "\n", + "\t\t# 4. If the Linked List is empty, then \n", + "\t\t# make the new node as head \n", + "\t\tif self.head is None: \n", + "\t\t\tnew_node.prev = None\n", + "\t\t\tself.head = new_node \n", + "\t\t\treturn\n", + "\n", + "\t\t# 5. Else traverse till the last node \n", + "\t\twhile (last.next is not None): \n", + "\t\t\tlast = last.next\n", + "\n", + "\t\t# 6. Change the next of last node \n", + "\t\tlast.next = new_node \n", + "\t\t# 7. Make last node as previous of new node */ \n", + "\t\tnew_node.prev = last \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/data_structures/Linked_list/Python/Linked List Traversal.ipynb b/data_structures/Linked_list/Python/Linked List Traversal.ipynb new file mode 100644 index 0000000000..cbb4f1bc51 --- /dev/null +++ b/data_structures/Linked_list/Python/Linked List Traversal.ipynb @@ -0,0 +1,91 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + } + ], + "source": [ + "# A simple Python program for traversal of a linked list \n", + " \n", + "# Node class \n", + "class Node: \n", + " \n", + " # Function to initialise the node object \n", + " def __init__(self, data): \n", + " self.data = data # Assign data \n", + " self.next = None # Initialize next as null \n", + " \n", + " \n", + "# Linked List class contains a Node object \n", + "class LinkedList: \n", + " \n", + " # Function to initialize head \n", + " def __init__(self): \n", + " self.head = None\n", + " \n", + " # This function prints contents of linked list \n", + " # starting from head \n", + " def printList(self): \n", + " temp = self.head \n", + " while (temp): \n", + " print(temp.data) \n", + " temp = temp.next\n", + " \n", + " \n", + "# Code execution starts here \n", + "if __name__=='__main__': \n", + " \n", + " # Start with the empty list \n", + " llist = LinkedList() \n", + " \n", + " llist.head = Node(1) \n", + " second = Node(2) \n", + " third = Node(3) \n", + " \n", + " llist.head.next = second; # Link first node with second \n", + " second.next = third; # Link second node with the third node \n", + " \n", + " llist.printList() " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/data_structures/Linked_list/Python/Simple Linked List.ipynb b/data_structures/Linked_list/Python/Simple Linked List.ipynb new file mode 100644 index 0000000000..7c2ef51683 --- /dev/null +++ b/data_structures/Linked_list/Python/Simple Linked List.ipynb @@ -0,0 +1,109 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# A simple Python program to introduce a linked list \n", + " \n", + "# Node class \n", + "class Node: \n", + " \n", + " # Function to initialise the node object \n", + " def __init__(self, data): \n", + " self.data = data # Assign data \n", + " self.next = None # Initialize next as null \n", + " \n", + " \n", + "# Linked List class contains a Node object \n", + "class LinkedList: \n", + " \n", + " # Function to initialize head \n", + " def __init__(self): \n", + " self.head = None\n", + " \n", + " \n", + "# Code execution starts here \n", + "if __name__=='__main__': \n", + " \n", + " # Start with the empty list \n", + " llist = LinkedList() \n", + " \n", + " llist.head = Node(1) \n", + " second = Node(2) \n", + " third = Node(3) \n", + " \n", + " ''' \n", + " Three nodes have been created. \n", + " We have references to these three blocks as head, \n", + " second and third \n", + " \n", + " llist.head second third \n", + " | | | \n", + " | | | \n", + " +----+------+ +----+------+ +----+------+ \n", + " | 1 | None | | 2 | None | | 3 | None | \n", + " +----+------+ +----+------+ +----+------+ \n", + " '''\n", + " \n", + " llist.head.next = second; # Link first node with second \n", + " \n", + " ''' \n", + " Now next of first Node refers to second. So they \n", + " both are linked. \n", + " \n", + " llist.head second third \n", + " | | | \n", + " | | | \n", + " +----+------+ +----+------+ +----+------+ \n", + " | 1 | o-------->| 2 | null | | 3 | null | \n", + " +----+------+ +----+------+ +----+------+ \n", + " '''\n", + " \n", + " second.next = third; # Link second node with the third node \n", + " \n", + " ''' \n", + " Now next of second Node refers to third. So all three \n", + " nodes are linked. \n", + " \n", + " llist.head second third \n", + " | | | \n", + " | | | \n", + " +----+------+ +----+------+ +----+------+ \n", + " | 1 | o-------->| 2 | o-------->| 3 | null | \n", + " +----+------+ +----+------+ +----+------+ \n", + " '''" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list.py b/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list.py new file mode 100644 index 0000000000..0382fe24cd --- /dev/null +++ b/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list.py @@ -0,0 +1,107 @@ +# linked list code +# creating a node +class node: + def __init__(self, data): + self.data = data + self.next = None + +class linkedlist: + def __init__(self): + self.head = None #creating a header + + def search(self,data): #find the node with the given data in the list + list_cp = self + count = 0 # the first element has index 0 + + while (list_cp): + if list_cp.head.data == data: + return count + else: + list_cp.deletion(0) + count = count + 1 + return -1 # if not found in the list, return -1 + + + #inserting a new node at the beginning + def push_front(self, new_data): + new_node = node(new_data) + new_node.next = self.head + self.head = new_node + + #inserting a new node after a node + def push_after(self, prev_data, new_data): + + #checking whether previous node exists + position = self.search(prev_data) + if position == -1: + print('Given node is not found in list.\n') + return + + new_node = node(new_data) + + #Make next of new Node as next of previous node + temp = self.head # issue here, the original list copy won't be remembered + for i in range(position-1): + temp = temp.next + + #make next of previous node as new node + temp.next = new_node + + + # append new node at the end + def push_end(self, new_data): + + new_node = node(new_data) + + #If the Linked List is empty, then make the new node as head + if self.head is None: + self.head = new_node + return + + #otherwise traverse to the last node + end = self.head + while (end.next): + end = end.next + + #Change the next of last node + end.next = new_node + + def deletion(self, position): + + #check if linked list is empty + if self.head == None: + return + + # store header + temp = self.head + + # If header is removed + if position == 0: + self.head = temp.next + temp = None + return + + #previous node to the node to be deleted + for i in range(position -1 ): + temp = temp.next + if temp is None: + break + + # If position is more than number of nodes + if temp is None and temp.next is None: + return + + + # store pointer to the next of node to be deleted + next = temp.next.next + + # remove node from the linked list + temp.next = None + + temp.next = next + + def printing(self): + temp = self.head + while temp is not None: + print(temp.data) + temp = temp.next diff --git a/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list_test.py b/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list_test.py new file mode 100644 index 0000000000..b5124156cf --- /dev/null +++ b/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list_test.py @@ -0,0 +1,50 @@ +# test cases +def test_insert(): + list = linkedlist() + list.head = node('a') + list.push('b') + list.pushend('c') + node1 = node('c') + list.push_after(node1,'d') # How is prev_node defined here? + # Ideally node d should be inserted at the end of node c, being the last + # element of the list, but here it is not sucessfully inserted, such that the + # resulting list has only elements [a, b, c] and an error occurs for the fourth + # deletion. The documentation about push_after() function is not very clear. + + # The issue here is that the list doesn't recognize the prev_node is a node already + # in the list. If this cannot be detected, this function is not very useful. + + if list.head.data == 'b': + res = True + else: + res = False + + list.deletion(0) + + if list.head.data == 'a': + res = True + else: + res = False + + list.deletion(0) + + if list.head.data == 'c': + res = True + else: + res = False + + list.deletion(0) + + if list.head.data == 'd': + res = True + else: + res = False + + return res + +if __name__ == '__main__': + result = test_insert() + if result == True: + print('Insertion test passed') + else: + print('Insertion test failed') diff --git a/data_structures/Linked_list/Python/cycle_check.py b/data_structures/Linked_list/Python/cycle_check.py new file mode 100644 index 0000000000..1710a4e60f --- /dev/null +++ b/data_structures/Linked_list/Python/cycle_check.py @@ -0,0 +1,42 @@ +class LinkedListNode(object): + + def __init__(self, value): + self.value = value + self.nextnode = None + + +def cycle_check(node): + + marker1 = marker2 = node + + while marker2 != None and marker2.nextnode != None: + marker1 = marker1.nextnode + + marker2 = marker2.nextnode.nextnode + + if marker1 == marker2: + return True + + return False + +if __name__ == '__main__': + # CREATE CYCLE LIST + a = LinkedListNode(1) + b = LinkedListNode(2) + c = LinkedListNode(3) + + a.nextnode = b + b.nextnode = c + c.nextnode = a # Cycle Here! + + + # CREATE NON CYCLE LIST + x = LinkedListNode(1) + y = LinkedListNode(2) + z = LinkedListNode(3) + + x.nextnode = y + y.nextnode = z + + assert cycle_check(a) == True + assert cycle_check(x) == False diff --git a/data_structures/Linked_list/Python/danielcustduran_linked_list.py b/data_structures/Linked_list/Python/danielcustduran_linked_list.py new file mode 100644 index 0000000000..2159252836 --- /dev/null +++ b/data_structures/Linked_list/Python/danielcustduran_linked_list.py @@ -0,0 +1,107 @@ +"""The LinkedList code from before is provided below. +Add three functions to the LinkedList. +"get_position" returns the element at a certain position. +The "insert" function will add an element to a particular +spot in the list. +"delete" will delete the first element with that +particular value. +Then, use "Test Run" and "Submit" to run the test cases +at the bottom.""" + + +class Element(object): + def __init__(self, value): + self.value = value + self.next = None + + +class LinkedList(object): + def __init__(self, head=None): + self.head = head + + def append(self, new_element): + current = self.head + if self.head: + while current.next: + current = current.next + current.next = new_element + else: + self.head = new_element + + def get_position(self, position): + """Get an element from a particular position. + Assume the first position is "1". + Return "None" if position is not in the list.""" + current = self.head + counter_pos = 1 + if self.head: + while current: + if counter_pos == position: + return current + counter_pos += 1 + current = current.next + return None + + def insert(self, new_element, position): + """Insert a new node at the given position. + Assume the first position is "1". + Inserting at position 3 means between + the 2nd and 3rd elements.""" + current = self.head + counter_pos = 1 + if self.head: + last_node = None + while current: + if (position-1) == counter_pos: + temp_elem = current.next + current.next = new_element + new_element.next = temp_elem + break + last_node = current + current = current.next + counter_pos += 1 + + def delete(self, value): + """Delete the first node with a given value.""" + current = self.head + if self.head: + while current: + if current.value == value: + next_node = current.next + current.next = None + self.head = next_node + current = self.head + last_node = current + return + current = current.next + + +# Test cases +# Set up some Elements +e1 = Element(1) +e2 = Element(2) +e3 = Element(3) +e4 = Element(4) + +# Start setting up a LinkedList +ll = LinkedList(e1) +ll.append(e2) +ll.append(e3) + +# Test get_position +# Should print 3 +# Should also print 3 +print(ll.get_position(3).value) + +# Test insert +ll.insert(e4, 3) +# Should print 4 now +print(ll.get_position(3).value) +# Test delete +ll.delete(1) +# Should print 2 now +print(ll.get_position(1).value) +# Should print 4 now +print(ll.get_position(2).value) +# Should print 3 now +print(ll.get_position(3).value) diff --git a/data_structures/Linked_list/Python/double_linked_list.py b/data_structures/Linked_list/Python/double_linked_list.py new file mode 100644 index 0000000000..366268f56f --- /dev/null +++ b/data_structures/Linked_list/Python/double_linked_list.py @@ -0,0 +1,71 @@ +class Node(object): + def __init__(self, value): + self.value=value + self.next=None + self.prev=None + +class List(object): + def __init__(self): + self.head=None + self.tail=None + + def insert(self,n,x): + #Not actually perfect: how do we prepend to an existing list? + if n!=None: + x.next=n.next + n.next=x + x.prev=n + if x.next!=None: + x.next.prev=x + if self.head==None: + self.head=self.tail=x + x.prev=x.next=None + elif self.tail==n: + self.tail=x + + def display(self): + values=[] + n=self.head + while n!=None: + values.append(str(n.value)) + n=n.next + print ("List: ",",".join(values)) + + def removeNode(self, node_delete): + """This function recieves a node and is responsible + for deleting it and reconecting the nodes before and after it.""" + prev = node_delete.prev + nxt = node_delete.next + + if(prev != None): + prev.next = nxt + if(nxt != None): + nxt.prev = prev + + def removeRepeated(self): + """this function uses a nested while loop to find + the repeated values. every time one is found the method + removeNode is called to remove the repeated node""" + aux = self.head + + while(aux != None): + aux2 = aux.next #needs to be .next otherwise it will compare the value on aux with itself + + while (aux2 != None): + + if(aux2.value == aux.value): + self.removeNode(aux2) + aux2 = aux2.next + + aux = aux.next + return self + + def toNativeList(self): + """This method creates a list with all the nodes + to use in the unit testing""" + n = self.head + out = [] + while(n != None): + out += [n.value] + n = n.next + return out \ No newline at end of file diff --git a/data_structures/Linked_list/Python/double_linked_list_test.py b/data_structures/Linked_list/Python/double_linked_list_test.py new file mode 100644 index 0000000000..a0408ed7d2 --- /dev/null +++ b/data_structures/Linked_list/Python/double_linked_list_test.py @@ -0,0 +1,23 @@ +from week5_ex1_basic import * +import unittest + +class TestMyMethods(unittest.TestCase): + + def testNoRepeated(self): + l=List() + l.insert(None, Node(4)) + l.insert(l.head,Node(6)) + l.insert(l.head,Node(8)) + + self.assertEqual(l.removeRepeated().toNativeList(), [4,8,6]) + + def testRepeated(self): + l=List() + l.insert(None, Node(4)) + l.insert(l.head,Node(6)) + l.insert(l.head,Node(8)) + l.insert(l.head,Node(6)) + + self.assertEqual(l.removeRepeated().toNativeList(), [4,6,8]) + +unittest.main() \ No newline at end of file diff --git a/data_structures/Linked_list/Python/linked_list.py b/data_structures/Linked_list/Python/linked_list.py new file mode 100644 index 0000000000..9f1cdc9390 --- /dev/null +++ b/data_structures/Linked_list/Python/linked_list.py @@ -0,0 +1,153 @@ +from __future__ import print_function + + +class LinkedList: + class Node: + next_node = None + data = None + + def compare_to(self, node): + return node.data == self.data + + def __init__(self, data, next_node): + self.data = data + self.next_node = next_node + + + class NoSuchNodeException(Exception): + pass + + + head = None + list_size = 0 + + def __init__(self): + pass + + + def size(self): + """ + This methods returns the size of the linked list. + :return: The size of the linked list. That is to say; the amount of elements in the linked list. + """ + return self.list_size + + + def is_empty(self): + """ + This methods determines whether the list is empty, which means it holds no values. + :return: True if the list is empty; False otherwise. + """ + return self.list_size == 0 + + + def get_first(self): + """ + This method returns the first element of the list. + :return: The first element of the list. + """ + if self.is_empty(): + raise self.NoSuchNodeException() + + return self.head.data + + + def getNode(self, i): + """ + This method takes an index and finds the node residing at the given index. + Raises an NoSuchNodeException() if there is no such element. + :param i: The index of the node. + :return: The ith node of the list. + """ + if i < 0 or i > self.list_size - 1: + raise self.NoSuchNodeException() + + current = 0 + p = self.head + + while current < i: + p = p.next_node + current += 1 + + return p + + + def add_first(self, data): + """ + This method adds a node to the front of the list. + :param data: The data of the node to add. + """ + + node = self.Node(data, self.head) + self.head = node + + self.list_size += 1 + + + def add_last(self, data): + """ + This method adds a node to the back of the list. + :param data: The data of the node to add. + """ + node = self.Node(data, None) + + if self.is_empty(): + self.head = node + else: + tail = self.getNode(self.list_size - 1) + tail.next_node = node + + self.list_size += 1 + + + def remove_first(self): + """ + This method removes the first element of the list. + :return: The value of the first element. + """ + if self.is_empty(): + raise self.NoSuchNodeException() + + tmp_val = self.head.data + self.head = self.head.next_node + self.list_size -= 1 + return tmp_val + + + def remove_last(self): + """ + This method removes the last element of the list. + :return: The value of the removed element. + """ + if self.is_empty(): + raise self.NoSuchNodeException() + + tail = self.getNode(self.list_size - 1) + tail_data = tail.data + + if self.list_size == 1: + self.head = None + else: + before_tail = self.getNode(self.list_size - 2) + before_tail.next_node = None + + self.list_size -= 1 + + return tail_data + + + def print_list(self): + """ + This method prints a list which a newline after each element. + """ + p = self.head + i = 0 + + while i < self.size(): + print(p.data) + i += 1 + p = p.next_node + + + + diff --git a/data_structures/Linked_list/README.md b/data_structures/Linked_list/README.md new file mode 100644 index 0000000000..78778a83d7 --- /dev/null +++ b/data_structures/Linked_list/README.md @@ -0,0 +1,18 @@ +In computer science, a linked list is a linear collection of data elements, in which linear order is not given by their physical placement in memory. Each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence during iteration. More complex variants add additional links, allowing efficient insertion or removal from arbitrary element references. + +## Single linked list +Singly linked lists contain nodes which have a data field as well as a 'next' field, which points to the next node in line of nodes. Operations that can be performed on singly linked lists include insertion, deletion and traversal. + +![](https://upload.wikimedia.org/wikipedia/commons/6/6d/Singly-linked-list.svg) + +## Double linked list +In a 'doubly linked list', each node contains, besides the next-node link, a second link field pointing to the 'previous' node in the sequence. The two links may be called 'forward('s') and 'backwards', or 'next' and 'prev'('previous'). + +![](https://upload.wikimedia.org/wikipedia/commons/5/5e/Doubly-linked-list.svg) + +## Circular linked list +In the last node of a list, the link field often contains a null reference, a special value used to indicate the lack of further nodes. A less common convention is to make it point to the first node of the list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is said to be 'open' or 'linear'. + +![](https://upload.wikimedia.org/wikipedia/commons/d/df/Circularly-linked-list.svg) + +[Credits](https://en.wikipedia.org/wiki/Linked_list) diff --git a/data_structures/Linked_list/Read_Me.md b/data_structures/Linked_list/Read_Me.md new file mode 100644 index 0000000000..2f86262e3a --- /dev/null +++ b/data_structures/Linked_list/Read_Me.md @@ -0,0 +1,15 @@ +Definition: + +Singly linked list can be defined as the collection of ordered set of elements. The number of elements may vary according to need of the program. A node in the singly linked list consist of two parts: data part and link part. Data part of the node stores actual information that is to be represented by the node while the link part of the node stores the address of its immediate successor. + +One way chain or singly linked list can be traversed only in one direction. In other words, we can say that each node contains only next pointer, therefore we can not traverse the list in the reverse direction. + +Advantages over arrays: + +Dynamic size +Ease of insertion/deletion +Drawbacks: + +Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists efficiently with its default implementation. Read about it here. +Extra memory space for a pointer is required with each element of the list. +Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists. \ No newline at end of file diff --git a/data_structures/Linked_list/go/DoublyLinkedList.go b/data_structures/Linked_list/go/DoublyLinkedList.go new file mode 100644 index 0000000000..d990cbac18 --- /dev/null +++ b/data_structures/Linked_list/go/DoublyLinkedList.go @@ -0,0 +1,133 @@ +package main + +import "fmt" + +// Node holds a Value of type int as well as a pointer to the node in +// front (Next) and a pointer to the node behind (Previous) it. These +// two pointers are the foundation of a doubly linked list. +type Node struct { + Value int + Next, Previous *Node +} + +// DoublyLinkedList holds only two pointers, one to the Head node and +// one to the Tail node of a list. Head and Tail will point to the +// same node if a list contains only that single node. +type DoublyLinkedList struct { + Head, Tail *Node +} + +// LoneNode is a helper function that adds a single node to a +// DoublyLinkedList. Since it's the only node in the list it becomes +// both the Head and Tail. +func (d *DoublyLinkedList) LoneNode(v int) { + newNode := &Node{v, nil, nil} + d.Head = newNode + d.Tail = newNode +} + +// Find searches for a Node in the list containing the Value v and +// returns a pointer to that Node. +func (d *DoublyLinkedList) Find(v int) *Node { + for node := d.Head; node != nil; node = node.Next { + if node.Value == v { + return node + } + } + + return nil +} + +// InsertBefore creates a new Node with the Value v and inserts it +// before node. If node is the Head then the new Node will become the +// Head. +func (d *DoublyLinkedList) InsertBefore(node *Node, v int) { + if node == d.Head { + newNode := &Node{v, node, nil} + node.Previous = newNode + d.Head = newNode + return + } + + newNode := &Node{v, node, node.Previous} + node.Previous.Next = newNode + node.Previous = newNode +} + +// InsertAfter creates a new Node with the Value v and inserts it +// after node. If node is the Tail then the new Node will become the +// Tail. +func (d *DoublyLinkedList) InsertAfter(node *Node, v int) { + if node == d.Tail { + newNode := &Node{v, nil, node} + node.Next = newNode + d.Tail = newNode + return + } + + newNode := &Node{v, node.Next, node} + node.Next.Previous = newNode + node.Next = newNode +} + +// InsertHead inserts a new Node with the Value v as the Head of the +// list. If there is currently no Head (i.e. the list is empty) then +// this new Node becomes both the Head and the Tail of a single node +// list, otherwise the new Node is inserted before the current Head. +func (d *DoublyLinkedList) InsertHead(v int) { + if d.Head == nil { + d.LoneNode(v) + return + } + + d.InsertBefore(d.Head, v) +} + +// InsertTail inserts a new Node with the Value v as the Tail of the +// list. If there is currently no Tail (i.e. the list is empty) then +// this new Node becomes both the Head and the Tail of a single node +// list, otherwise the new Node is inserted after the current Tail. +func (d *DoublyLinkedList) InsertTail(v int) { + if d.Tail == nil { + d.LoneNode(v) + return + } + + d.InsertAfter(d.Tail, v) +} + +// Print list from Head to Tail. +func (d *DoublyLinkedList) PrintFoward() { + for node := d.Head; node != nil; node = node.Next { + fmt.Printf("%d", node.Value) + } + fmt.Println() +} + +// Print list from Tail to Head. +func (d *DoublyLinkedList) PrintReverse() { + for node := d.Tail; node != nil; node = node.Previous { + fmt.Printf("%d", node.Value) + } + fmt.Println() +} + +func main() { + var dll DoublyLinkedList + + dll.InsertHead(2) + dll.InsertTail(5) + + dll.InsertAfter(dll.Find(2), 3) + dll.InsertBefore(dll.Find(5), 4) + + dll.InsertTail(7) + + dll.InsertBefore(dll.Find(7), 6) + + dll.InsertHead(1) + dll.InsertTail(8) + + dll.PrintFoward() + dll.PrintReverse() +} diff --git a/data_structures/Linked_list/go/Linkedlist.go b/data_structures/Linked_list/go/Linkedlist.go new file mode 100644 index 0000000000..6bad5c840b --- /dev/null +++ b/data_structures/Linked_list/go/Linkedlist.go @@ -0,0 +1,102 @@ +package main + +import "fmt" + +/* v is the value of node; next is the pointer to next node */ +type node struct { + v int + next *node +} + +/* first node, called head. It points from first node to last node */ +var head *node = nil + +func (l *node) pushFront(val int) *node { + /* if there's no nodes, head points to l (first node) */ + if head == nil { + l.v = val + l.next = nil + head = l + return l + } else { + /* create a new node equals to head */ + nnode := new(node) + nnode = head + /* create a second node with new value and `next -> nnode` + * is this way, nnode2 is before nnode + */ + nnode2 := &node { + v: val, + next: nnode, + } + /* now head is equals nnode2 */ + head = nnode2 + return head + } +} + +func (l *node) pushBack(val int) *node { + /* if there's no nodes, head points to l (first node) */ + if head == nil { + l.v = val + l.next = nil + head = l + return l + } else { + /* read all list to last node */ + for l.next != nil { + l = l.next + } + /* allocate a new portion of memory */ + l.next = new(node) + l.next.v = val + l.next.next = nil + return l + } +} + +func (l *node) popFront() *node { + if head == nil { + return head + } + /* create a new node equals to first node pointed by head */ + cpnode := new(node) + cpnode = head.next + + /* now head is equals cpnode (second node) */ + head = cpnode + + return head +} + +func (l *node) popBack() *node { + if head == nil { + return head + } + /* create a new node equals to head */ + cpnode := new(node) + cpnode = head + + /* read list to the penultimate node */ + for cpnode.next.next != nil { + cpnode = cpnode.next + } + /* the penultimate node points to null. In this way the last node is deleted */ + cpnode.next = nil + return head +} + +func main() { + lista := new(node) + lista.pushBack(25).pushBack(24).pushBack(32) /* lista: 25 24 32 */ + lista.pushBack(56) /* lista: 25 24 32 56 */ + lista.pushFront(36) /* lista: 36 25 24 32 56 */ + lista.popFront() /* lista: 25 24 32 56 */ + lista.popBack() /* lista: 25 24 32 */ + + /* read the list until head is not nil */ + for head != nil { + fmt.Printf("%d ",head.v) + head = head.next /*head points to next node */ + } +} diff --git a/data_structures/Linked_list/java/CircularlyLinkedList.java b/data_structures/Linked_list/java/CircularlyLinkedList.java new file mode 100644 index 0000000000..09ebe82f71 --- /dev/null +++ b/data_structures/Linked_list/java/CircularlyLinkedList.java @@ -0,0 +1,158 @@ +public class CircularlyLinkedList implements Cloneable { + + private static class Node { + + private E element; + + public Node(E e, Node n, Node p) { + element = e; + next = n; + } + + public E getElement() { return element; } + + public Node getNext() { return next; } + + public Node getPrevious() { return previous; } + + public void setNext(Node n) { next = n; } + public void setPrevious(Node p){previous = p;} + } + + private Node head = null; + + private Node tail = null; + + public CircularlyLinkedList() { } + + public int size() { //size is not perfect in terms of performance + //however it's just another way to do it as an idea + // if you want, you can just add an size int and count it. + int cnt = 0; + Node cntPtr = head; + if (cntPtr!=null) + cnt++; + while (!(cntPtr==tail)){ + cntPtr = cntPtr.next; + cnt++; + } + return cnt; } + + public boolean isEmpty() { return size() == 0; } + + + public E first() { // returns (but does not remove) the first element + if (isEmpty()) return null; + return head.getElement(); + } + + public E last() { // returns (but does not remove) the last element + if (isEmpty()) return null; + return tail.getElement(); + } + + public void addFirst(E e) { // adds element e to the front of the list + if(tail!=null){ + head = new Node<>(e, head, tail); + } + else{ + head = new Node<>(e, head, head); // create and link a new node + if (size() == 2) // ADDS FIRST ELEMENT UNCONTROLLED AND EMPTY ELEMENT SO IT'S 2 + tail = head; // special case: new node becomes tail also + } + } + + public void addLast(E e) { // adds element e to the end of the list + Node newest = new Node<>(e, head, tail); // node will eventually be the tail + if (isEmpty()) + head = newest; // special case: previously empty list + else + tail.setNext(newest); // new node after existing tail + tail = newest; // new node becomes the tail + + } + public void addBetween(E element, Node p, Node n){ + Node newNode = new Node(element, n, p); + p.setNext(newNode); + n.setPrevious(newNode); + } + + public E removeFirst() { // removes and returns the first element + if (isEmpty()) return null; // nothing to remove + E answer = head.getElement(); + head = head.getNext(); // will become null if list had only one node + if (size() == 0) + tail = null; // special case as list is now empty + return answer; + } + + public E removeTail(){ + if (isEmpty()) return null; + E answer = tail.getElement(); + tail=tail.getPrevious(); + if (size() == 0) + tail = null; + return answer; + } + public E removeElement(Node node){ + node.getPrevious().setNext(node.getNext()); + node.getNext().setPrevious(node.getPrevious()); + return node.getElement(); + } + + @SuppressWarnings({"unchecked"}) + public boolean equals(Object o) { + if (o == null) return false; + if (getClass() != o.getClass()) return false; + CircularlyLinkedList other = (CircularlyLinkedList) o; // use nonparameterized type + if (size() != other.size()) return false; + Node walkA = head; // traverse the primary list + Node walkB = other.head; // traverse the secondary list + while (walkA != null) { + if (!walkA.getElement().equals(walkB.getElement())) return false; //mismatch + walkA = walkA.getNext(); + walkB = walkB.getNext(); + } + return true; // if we reach this, everything matched successfully + } + + @SuppressWarnings({"unchecked"}) + public CircularlyLinkedList clone() throws CloneNotSupportedException { + CircularlyLinkedList other = new CircularlyLinkedList(); + if (size() > 0) { + other.addFirst(head.getElement()); + Node cloningElement = head.next; + for(int i = 0; i < size()-1; i++){ + other.addLast(cloningElement.getElement()); + cloningElement = cloningElement.next; + } + } + return other; + + } + + public int hashCode() { + int h = 0; + for (Node walk=head; walk != null; walk = walk.getNext()) { + h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code + h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code + } + return h; + } + + public String toString() { + StringBuilder sb = new StringBuilder("("); + Node walk = head; + while (walk != tail) { //we need to run it till the last element, if null; the program will work forever + sb.append(walk.getElement()); + if (walk != tail) + sb.append(", "); + walk = walk.getNext(); + } + if(walk==tail){ + sb.append(walk.getElement()); + } + sb.append(")"); + return sb.toString(); + } +} \ No newline at end of file diff --git a/data_structures/Linked_list/java/Delete_LinkedList.java b/data_structures/Linked_list/java/Delete_LinkedList.java new file mode 100644 index 0000000000..48cdedadc8 --- /dev/null +++ b/data_structures/Linked_list/java/Delete_LinkedList.java @@ -0,0 +1,41 @@ +package linkedlist; + +class LinkedList { + Node head; + + class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + next = null; + } + } + + public void push(int data) { + Node new_node = new Node(data); + new_node.next = head; + head = new_node; + } + public void printList() { + Node n = head; + while(n != null) { + System.out.print(n.data+" "); + n = n.next; + } + } + public void deleteList() { + head = null; + } + public static void main(String args[]) { + LinkedList ll = new LinkedList(); + ll.push(2); + ll.push(3); + ll.push(4); + ll.printList(); + System.out.println("After Deleting"); + ll.deleteList(); + ll.printList(); + } +} diff --git a/data_structures/Linked_list/java/DoublyLinkedList.java b/data_structures/Linked_list/java/DoublyLinkedList.java new file mode 100644 index 0000000000..6fb33b281e --- /dev/null +++ b/data_structures/Linked_list/java/DoublyLinkedList.java @@ -0,0 +1,206 @@ + +public class DoublyLinkedList { + + private T data; + private Node head; + private Node tail; + private int size = 0; + + /** + * Constructs an empty DoublyLinkedList + */ + public DoublyLinkedList() { + + this.head = new Node(); + this.tail = new Node(); + this.size = 0; + + this.head.next = tail; + this.tail.previous = head; + + } + + /** + * Adds a value at the end of the list. + * + * @param data The value to add at the end of the list. + */ + public void addLast(T data) { + Node newNode = new Node(data); + Node temp = tail.previous; + + temp.next = newNode; + newNode.previous = temp; + newNode.next = tail; + tail.previous = newNode; + size++; + } + + /** + * Adds a value at the beginning of the list. + * + * @param data The value to add at the beginning of the list. + */ + public void addFirst(T data) { + Node newNode = new Node(data); + Node temp = head.next; + + head.next = newNode; + newNode.previous = head; + temp.previous = newNode; + newNode.next = temp; + size++; + } + + /** + * Adds the value at the specified index in the list. + * + * @param i The index to insert the value at. + * @param data The value to insert. + */ + public void addAtIndex(int i, T data) { + if (i > size || i < 0) { + throw new IndexOutOfBoundsException(); + } else if (this.isEmpty() || i == 0) { + this.addFirst(data); + return; + } else if (i == size) { + this.addLast(data); + return; + } + + Node currentNode = getNodeAtIndex(i); + Node newNode = new Node(data); + + newNode.previous = currentNode.previous; + newNode.previous.next = newNode; + newNode.next = currentNode; + newNode.next.previous = newNode; + size++; + } + + /** + * Helper method used for getting the Node at a specified index in the list. + * + * @param i The index of the Node to retrieve. + * @return The Node at the given index. + */ + private Node getNodeAtIndex(int i) { + Node currentNode; + if (i > size - 1 || i < 0) { + throw new IndexOutOfBoundsException(); + } + + // To allow for faster list traversal, we can traverse from the head or the tail + // based on which one the given index is closest to. + if (i < this.size / 2) { + currentNode = head.next; + int currentIndex = 0; + + while (currentIndex != i) { + currentNode = currentNode.next; + currentIndex++; + } + } else { + currentNode = tail.previous; + int currentIndex = this.size - 1; + + while (currentIndex != i) { + currentNode = currentNode.previous; + currentIndex--; + } + } + + return currentNode; + } + + /** + * Use to get the value in the last at the given index. + * + * @param i The index to get the value from. + * @return + */ + public T get(int i) { + if (i > size - 1 || i < 0) { + throw new IndexOutOfBoundsException(); + } + return getNodeAtIndex(i).data; + } + + /** + * Sets the data of the value at the given index. + * + * @param i + * @param data + */ + public void set(int i, T data) { + getNodeAtIndex(i).data = data; + } + + /** + * Removes the Node at the given index from the list. If there is no longer + * anything referencing the object, JVM garbage collection will git rid of + * it. + * + * @param i The index of the Node to remove.0 + */ + public void remove(int i) { + if (i > size - 1 || i < 0) { + throw new IndexOutOfBoundsException(); + } + + Node removeMe = getNodeAtIndex(i); + removeMe.previous.next = removeMe.next; + removeMe.next.previous = removeMe.previous; + size--; + } + + /** + * @return The number of values in the list + */ + public int size() { + return this.size; + } + + /** + * @return True if the list is empty, false if not. + */ + public boolean isEmpty() { + return size == 0; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + Node currentNode = head.next; + + while (currentNode != tail) { + sb.append(currentNode.data.toString()); + if (currentNode.next != tail) { + sb.append(", "); + } + currentNode = currentNode.next; + } + + return sb.toString(); + } + + /** + * For creating the nodes of a DoublyLinkedList + */ + private class Node { + + T data; + Node next; + Node previous; + + Node() { + } + + Node(T data) { + this.data = data; + } + } + +} diff --git a/data_structures/Linked_list/java/Linked_List.java b/data_structures/Linked_list/java/Linked_List.java new file mode 100644 index 0000000000..0ff0cb72ad --- /dev/null +++ b/data_structures/Linked_list/java/Linked_List.java @@ -0,0 +1,153 @@ +public class Linked_List> { + + //class for node of a linked list + private class Node implements Comparable { + T data; + Node next; + + //constructor + Node(T data, Node next) { + this.data = data; + this.next = next; + } + + public int compareTo(Linked_List.Node node) { + return this.data.compareTo(node.data); + } + } + + private Node head; + private Node tail; + private int size; + + //constructor + public Linked_List() { + this.head = null; + this.tail = null; + size = 0; + } + + //method to get size of the linked list + public int size() { + return this.size; + } + + //method to check if linked list is empty + public boolean isEmpty() { + return size() == 0; + } + + //method to get first element of the linked list + public T getFirst() throws Exception { + if (isEmpty()) { + throw new Exception("Invalid Operation"); + } + + return this.head.data; + } + + //method to get last element of the linked list + public T getLast() throws Exception { + if (isEmpty()) { + throw new Exception("Invalid Operation"); + } + + return this.tail.data; + } + + //method to get element at an index of the linked list + private Node getNodeAt(int idx) throws Exception { // O(N) complexity + if (idx < 0 || idx >= this.size()) { + throw new Exception("Invalid Operation"); + } + + int counter = 0; + Node temp = this.head; + + while (counter < idx) { + temp = temp.next; + counter++; + } + + return temp; + } + + //method to add new element at beginning of the linked list + public void addFirst(T data) { + Node newNode = new Node(data, this.head); + this.head = newNode; + if (isEmpty()) { + this.tail = newNode; + } + this.size++; + } + + //method to add new element at end of the linked list + public void addLast(T data) { + Node newNode = new Node(data, null); + + if (isEmpty()) { + this.head = newNode; + this.tail = newNode; + } else { + this.tail.next = newNode; + this.tail = newNode; + } + this.size++; + } + + //method to remove element from beginning of the linked list + public T removeFirst() throws Exception { + if (isEmpty()) { + throw new Exception("Invalid Operation"); + } + + T temp = this.head.data; + this.head = this.head.next; + + if (this.size() == 1) + this.tail = null; + + size--; + return temp; + } + + //method to remove element from end of the linked list + public T removeLast() throws Exception { + if (isEmpty()) { + throw new Exception("Invalid Operation"); + } + + T tempdata = this.tail.data; + + if (this.size() == 1) { + this.head = null; + this.tail = null; + } else { + Node temp = getNodeAt(this.size() - 2); + temp.next = null; + this.tail = temp; + } + this.size--; + return tempdata; + } + + //method to display linked list from starting to end + public void display() { + System.out.println(this); + } + + public String toString() { + String retval = ""; + + Node temp = this.head; + while (temp != null) { + retval += temp.data + " => "; + temp = temp.next; + } + retval += "END"; + + return retval; + } + +} diff --git a/data_structures/Linked_list/java/Linked_List_Test.java b/data_structures/Linked_list/java/Linked_List_Test.java new file mode 100644 index 0000000000..7eb239a479 --- /dev/null +++ b/data_structures/Linked_list/java/Linked_List_Test.java @@ -0,0 +1,31 @@ +public class Linked_List_Test { + + public static void main(String[] args) throws Exception { + Linked_List list = new Linked_List<>(); + + list.display(); + + list.addFirst("Universe"); + list.addFirst("Code"); + list.addFirst("hey"); + list.display(); + + list.addLast("Like"); + list.addLast("Heaven"); + list.addLast("Whole"); + list.display(); + + System.out.println("first element: " +list.getFirst()); + System.out.println("last element: " +list.getLast()); + System.out.println("size of list: "+list.size()); + + list.removeFirst(); + list.display(); + + list.removeLast(); + list.display(); + + System.out.println("is empty: "+list.isEmpty()); + + } +} diff --git a/data_structures/Linked_list/java/reverse_link_list.java b/data_structures/Linked_list/java/reverse_link_list.java new file mode 100644 index 0000000000..e94e2ddf5a --- /dev/null +++ b/data_structures/Linked_list/java/reverse_link_list.java @@ -0,0 +1,21 @@ +// Reverse a linked list and return pointer to the head +// The input list will have at least one element +// Node is defined as +class Node { + int data; + Node next; +} + +Node Reverse(Node head) { + Node prev, nex , curr; + prev = null; + curr = head; + while(curr != null){ + nex = curr.next; + curr.next = prev; + prev = curr; + curr = nex; + } + head = prev; + return head; +} diff --git a/data_structures/Linked_list/javascript/LList.js b/data_structures/Linked_list/javascript/LList.js new file mode 100644 index 0000000000..2e415a349c --- /dev/null +++ b/data_structures/Linked_list/javascript/LList.js @@ -0,0 +1,45 @@ +/* + * Link List implementation in Javascript + */ + +function _P(value){ + console.log(value); +} +function Node(element){ + this.element = element; + this.next = null; +} + +function LList(){ + this.head = new Node("head"); + this.find = find; + this.insert = insert; + this.display = display; +} +function find(item){ + var currNode = this.head; + while(currNode.element != item){ + currNode = currNode.next; + } + return currNode; +} +function insert(newElement, item){ + var newNode = new Node(newElement); + var current = this.find(item); + newNode.next = current.next; + current.next = newNode; +} + +function display(){ + var currNode = this.head; + while(!(currNode.next == null)){ + _P(currNode.next.element); + currNode = currNode.next; + } +} + +var cities = new LList(); +cities.insert("Kolkata", "head"); +cities.insert("Mumbai", "Kolkata"); +cities.insert("Delhi", "Mumbai"); +cities.display(); \ No newline at end of file diff --git a/data_structures/Linked_list/javascript/linked_list_insertion.js b/data_structures/Linked_list/javascript/linked_list_insertion.js new file mode 100644 index 0000000000..5b6aeb7045 --- /dev/null +++ b/data_structures/Linked_list/javascript/linked_list_insertion.js @@ -0,0 +1,19 @@ +class LinkedList{ + constructor(value){ + this.head = null; + this.length = 0; + this.addToHead(value); + } + + addToHead(value){ + const newNode = {value}; + newNode.next = this.head; + this.head = newNode; + this.length++; + return this; + } + +} + +const list = new LinkedList(1); // Test +list.addToHead(2); // Test \ No newline at end of file diff --git a/data_structures/Linked_list/javascript/orinayo_linkedlist.js b/data_structures/Linked_list/javascript/orinayo_linkedlist.js new file mode 100644 index 0000000000..3e50b73f2e --- /dev/null +++ b/data_structures/Linked_list/javascript/orinayo_linkedlist.js @@ -0,0 +1,181 @@ +// Description +// Implement classes Node and Linked Lists + +class Node { + // Creates a class instance to represent a node. The node should have two properties, + // 'data' and 'next'. Accept both of these as arguments to the 'Node' constructor, + // then assign them to the instance as properties 'data' and 'next'. If 'next' is not + // provided to the constructor, then default its value to be 'null'. + constructor(data, next = null) { + this.data = data; + this.next = next; + } +} + +class LinkedList { + // Creates a class to represent a linked list. When created, a linked list should have + // *no* head node associated with it. The LinkedList instance will have one property, 'head', + // which is a reference to the first node of the linked list. By default 'head' should be 'null'. + constructor() { + this.head = null; + } + + // Creates a new Node from argument 'data' and assigns the resulting node to the 'head' property. + // Make sure to handle the case in which the linked list already has a node assigned to the 'head' property. + insertFirst(data) { + this.head = new Node(data, this.head); + } + + // Returns the number of nodes in the linked list. + size() { + let counter = 0; + let node = this.head; + + while (node) { + counter++; + node = node.next; + } + + return counter; + } + + // Returns the first node of the linked list. + getFirst() { + return this.head; + } + + // Returns the last node of the linked list + getLast() { + if (!this.head) { + return null; + } + + let node = this.head; + while (node) { + if (!node.next) { + return node; + } + node = node.next; + } + } + + // Empties the linked list of any nodes. + clear() { + this.head = null; + } + + // Removes only the first node of the linked list. The list's head should now be the second element. + removeFirst() { + if (!this.head) { + return; + } + + this.head = this.head.next; + } + + // Removes the last node of the chain + removeLast() { + if (!this.head) { + return; + } + + if (!this.head.next) { + this.head = null; + return; + } + + let previous = this.head; + let node = this.head.next; + while (node.next) { + previous = node; + node = node.next; + } + previous.next = null; + } + + // Inserts a new node with provided data at the end of the chain + insertLast(data) { + const last = this.getLast(); + + if (last) { + // There are some existing nodes in our chain + last.next = new Node(data); + } else { + // The chain is empty! + this.head = new Node(data); + } + } + + // Returns the node at the provided index + getAt(index) { + let counter = 0; + let node = this.head; + while (node) { + if (counter === index) { + return node; + } + + counter++; + node = node.next; + } + return null; + } + + // Removes node at the provided index + removeAt(index) { + if (!this.head) { + return; + } + + if (index === 0) { + this.head = this.head.next; + return; + } + + const previous = this.getAt(index - 1); + if (!previous || !previous.next) { + return; + } + previous.next = previous.next.next; + } + + // Create an insert a new node at provided index. If index is out of bounds, + // add the node to the end of the list. + insertAt(data, index) { + if (!this.head) { + this.head = new Node(data); + return; + } + + if (index === 0) { + this.head = new Node(data, this.head); + return; + } + + const previous = this.getAt(index - 1) || this.getLast(); + const node = new Node(data, previous.next); + previous.next = node; + } + + // Calls the provided function with every node of the chain and the index of the node. + forEach(fn) { + let node = this.head; + let counter = 0; + while (node) { + fn(node, counter); + node = node.next; + counter++; + } + } + + // Linked list should be compatible as the subject of a 'for...of' loop + *[Symbol.iterator]() { + let node = this.head; + while (node) { + yield node; + node = node.next; + } + } +} + +module.exports = { Node, LinkedList }; diff --git a/data_structures/Linked_list/javascript/orinayo_linkedlist.test.js b/data_structures/Linked_list/javascript/orinayo_linkedlist.test.js new file mode 100644 index 0000000000..e94e82f209 --- /dev/null +++ b/data_structures/Linked_list/javascript/orinayo_linkedlist.test.js @@ -0,0 +1,321 @@ +const L = require('./orinayo_linkedlist'); +const List = L.LinkedList; +const Node = L.Node; + +test('List is a class', () => { + expect(typeof List.prototype.constructor).toEqual('function'); +}); + +test('Node is a class', () => { + expect(typeof Node.prototype.constructor).toEqual('function'); +}); + +describe('A Node', () => { + test('has properties "data" and "next"', () => { + const node = new Node('a', 'b'); + expect(node.data).toEqual('a'); + expect(node.next).toEqual('b'); + }); +}); + +describe('Insert First', () => { + test('appends a node to the start of the list', () => { + const l = new List(); + l.insertFirst(1); + expect(l.head.data).toEqual(1); + l.insertFirst(2); + expect(l.head.data).toEqual(2); + }); +}); + +describe('Size', () => { + test('returns the number of items in the linked list', () => { + const l = new List(); + expect(l.size()).toEqual(0); + l.insertFirst(1); + l.insertFirst(1); + l.insertFirst(1); + l.insertFirst(1); + expect(l.size()).toEqual(4); + }); +}); + +describe('GetFirst', () => { + test('returns the first element', () => { + const l = new List(); + l.insertFirst(1); + expect(l.getFirst().data).toEqual(1); + l.insertFirst(2); + expect(l.getFirst().data).toEqual(2); + }); +}); + +describe('GetLast', () => { + test('returns the last element', () => { + const l = new List(); + l.insertFirst(2); + expect(l.getLast()).toEqual({ data: 2, next: null }); + l.insertFirst(1); + expect(l.getLast()).toEqual({ data: 2, next: null }); + }); +}); + +describe('Clear', () => { + test('empties out the list', () => { + const l = new List(); + expect(l.size()).toEqual(0); + l.insertFirst(1); + l.insertFirst(1); + l.insertFirst(1); + l.insertFirst(1); + expect(l.size()).toEqual(4); + l.clear(); + expect(l.size()).toEqual(0); + }); +}); + +describe('RemoveFirst', () => { + test('removes the first node when the list has a size of one', () => { + const l = new List(); + l.insertFirst('a'); + l.removeFirst(); + expect(l.size()).toEqual(0); + expect(l.getFirst()).toEqual(null); + }); + + test('removes the first node when the list has a size of three', () => { + const l = new List(); + l.insertFirst('c'); + l.insertFirst('b'); + l.insertFirst('a'); + l.removeFirst(); + expect(l.size()).toEqual(2); + expect(l.getFirst().data).toEqual('b'); + l.removeFirst(); + expect(l.size()).toEqual(1); + expect(l.getFirst().data).toEqual('c'); + }); +}); + +describe('RemoveLast', () => { + test('RemoveLast removes the last node when list is empty', () => { + const l = new List(); + expect(() => { + l.removeLast(); + }).not.toThrow(); + }); + + test('RemoveLast removes the last node when list is length 1', () => { + const l = new List(); + l.insertFirst('a'); + l.removeLast(); + expect(l.head).toEqual(null); + }); + + test('RemoveLast removes the last node when list is length 2', () => { + const l = new List(); + l.insertFirst('b'); + l.insertFirst('a'); + + l.removeLast(); + + expect(l.size()).toEqual(1); + expect(l.head.data).toEqual('a'); + }); + + test('RemoveLast removes the last node when list is length 3', () => { + const l = new List(); + l.insertFirst('c'); + l.insertFirst('b'); + l.insertFirst('a'); + l.removeLast(); + + expect(l.size()).toEqual(2); + expect(l.getLast().data).toEqual('b'); + }); +}); + +describe('InsertLast', () => { + test('adds to the end of the list', () => { + const l = new List(); + l.insertFirst('a'); + + l.insertLast('b'); + + expect(l.size()).toEqual(2); + expect(l.getLast().data).toEqual('b'); + }); +}); + +describe('GetAt', () => { + test('returns the node at given index', () => { + const l = new List(); + expect(l.getAt(10)).toEqual(null); + + l.insertLast(1); + l.insertLast(2); + l.insertLast(3); + l.insertLast(4); + + expect(l.getAt(0).data).toEqual(1); + expect(l.getAt(1).data).toEqual(2); + expect(l.getAt(2).data).toEqual(3); + expect(l.getAt(3).data).toEqual(4); + }); +}); + +describe('RemoveAt', () => { + test('removeAt doesnt crash on an empty list', () => { + const l = new List(); + expect(() => { + l.removeAt(0); + l.removeAt(1); + l.removeAt(2); + }).not.toThrow(); + }); + + test('removeAt doesnt crash on an index out of bounds', () => { + const l = new List(); + expect(() => { + const l = new List(); + l.insertFirst('a'); + l.removeAt(1); + }).not.toThrow(); + }); + + test('removeAt deletes the first node', () => { + const l = new List(); + l.insertLast(1); + l.insertLast(2); + l.insertLast(3); + l.insertLast(4); + expect(l.getAt(0).data).toEqual(1); + l.removeAt(0); + expect(l.getAt(0).data).toEqual(2); + }); + + test('removeAt deletes the node at the given index', () => { + const l = new List(); + l.insertLast(1); + l.insertLast(2); + l.insertLast(3); + l.insertLast(4); + expect(l.getAt(1).data).toEqual(2); + l.removeAt(1); + expect(l.getAt(1).data).toEqual(3); + }); + + test('removeAt works on the last node', () => { + const l = new List(); + l.insertLast(1); + l.insertLast(2); + l.insertLast(3); + l.insertLast(4); + expect(l.getAt(3).data).toEqual(4); + l.removeAt(3); + expect(l.getAt(3)).toEqual(null); + }); +}); + +describe('InsertAt', () => { + test('inserts a new node with data at the 0 index when the list is empty', () => { + const l = new List(); + l.insertAt('hi', 0); + expect(l.getFirst().data).toEqual('hi'); + }); + + test('inserts a new node with data at the 0 index when the list has elements', () => { + const l = new List(); + l.insertLast('a'); + l.insertLast('b'); + l.insertLast('c'); + l.insertAt('hi', 0); + expect(l.getAt(0).data).toEqual('hi'); + expect(l.getAt(1).data).toEqual('a'); + expect(l.getAt(2).data).toEqual('b'); + expect(l.getAt(3).data).toEqual('c'); + }); + + test('inserts a new node with data at a middle index', () => { + const l = new List(); + l.insertLast('a'); + l.insertLast('b'); + l.insertLast('c'); + l.insertLast('d'); + l.insertAt('hi', 2); + expect(l.getAt(0).data).toEqual('a'); + expect(l.getAt(1).data).toEqual('b'); + expect(l.getAt(2).data).toEqual('hi'); + expect(l.getAt(3).data).toEqual('c'); + expect(l.getAt(4).data).toEqual('d'); + }); + + test('inserts a new node with data at a last index', () => { + const l = new List(); + l.insertLast('a'); + l.insertLast('b'); + l.insertAt('hi', 2); + expect(l.getAt(0).data).toEqual('a'); + expect(l.getAt(1).data).toEqual('b'); + expect(l.getAt(2).data).toEqual('hi'); + }); + + test('insert a new node when index is out of bounds', () => { + const l = new List(); + l.insertLast('a'); + l.insertLast('b'); + l.insertAt('hi', 30); + + expect(l.getAt(0).data).toEqual('a'); + expect(l.getAt(1).data).toEqual('b'); + expect(l.getAt(2).data).toEqual('hi'); + }); +}); + +describe('ForEach', () => { + test('applies a transform to each node', () => { + const l = new List(); + + l.insertLast(1); + l.insertLast(2); + l.insertLast(3); + l.insertLast(4); + + l.forEach(node => { + node.data += 10; + }); + + expect(l.getAt(0).data).toEqual(11); + expect(l.getAt(1).data).toEqual(12); + expect(l.getAt(2).data).toEqual(13); + expect(l.getAt(3).data).toEqual(14); + }); +}); + +describe('for...of loops', () => { + test('works with the linked list', () => { + const l = new List(); + + l.insertLast(1); + l.insertLast(2); + l.insertLast(3); + l.insertLast(4); + + for (let node of l) { + node.data += 10; + } + + expect(l.getAt(0).data).toEqual(11); + expect(l.getAt(1).data).toEqual(12); + expect(l.getAt(2).data).toEqual(13); + expect(l.getAt(3).data).toEqual(14); + }); + + test('for...of works on an empty list', () => { + const l = new List(); + expect(() => { + for (let node of l) { + } + }).not.toThrow(); + }); +}); diff --git a/data_structures/Linked_list/kotlin/DoublyLinkedList.kt b/data_structures/Linked_list/kotlin/DoublyLinkedList.kt new file mode 100644 index 0000000000..65052ef9c6 --- /dev/null +++ b/data_structures/Linked_list/kotlin/DoublyLinkedList.kt @@ -0,0 +1,164 @@ +class DoublyLinkedList { + + private val head: Node + private val tail: Node + private var size = 0 + + val isEmpty: Boolean + get() = size == 0 + + init { + this.head = Node() + this.tail = Node() + this.size = 0 + + this.head.next = tail + this.tail.previous = head + } + + fun addTail(data: T) { + val newNode = Node(data) + val temp = tail.previous + + temp!!.next = newNode + newNode.previous = temp + newNode.next = tail + tail.previous = newNode + size++ + } + + fun addHead(data: T) { + val newNode = Node(data) + val temp = head.next + + head.next = newNode + newNode.previous = head + temp!!.previous = newNode + newNode.next = temp + size++ + } + + fun addAtIndex(i: Int, data: T) { + if (i > size || i < 0) { + throw IndexOutOfBoundsException() + } else if (this.isEmpty || i == 0) { + this.addHead(data) + return + } else if (i == size) { + this.addTail(data) + return + } + + val currentNode = getNodeAtIndex(i) + val newNode = Node(data) + + newNode.previous = currentNode!!.previous + newNode.previous!!.next = newNode + newNode.next = currentNode + newNode.next!!.previous = newNode + size++ + } + + private fun getNodeAtIndex(i: Int): Node? { + var currentNode: Node? + if (i > size - 1 || i < 0) { + throw IndexOutOfBoundsException() + } + + // To allow for faster list traversal, we can traverse from the head or the tail + // based on which one the given index is closest to. + if (i < this.size / 2) { + currentNode = head.next + var currentIndex = 0 + + while (currentIndex != i) { + currentNode = currentNode!!.next + currentIndex++ + } + } else { + currentNode = tail.previous + var currentIndex = this.size - 1 + + while (currentIndex != i) { + currentNode = currentNode!!.previous + currentIndex-- + } + } + + return currentNode + } + + operator fun get(i: Int): T { + if (i > size - 1 || i < 0) { + throw IndexOutOfBoundsException() + } + return getNodeAtIndex(i)!!.data!! + } + + operator fun set(i: Int, data: T) { + getNodeAtIndex(i)!!.data = data + } + + fun deleteAtIndex(i: Int) { + if (i > size - 1 || i < 0) { + throw IndexOutOfBoundsException() + } + + val removeMe = getNodeAtIndex(i) + removeMe!!.previous!!.next = removeMe.next + removeMe.next!!.previous = removeMe.previous + size-- + } + + fun size(): Int { + return this.size + } + + override fun toString(): String { + val sb = StringBuilder() + + var currentNode = head.next + + while (currentNode !== tail) { + sb.append(currentNode!!.data.toString()) + if (currentNode.next !== tail) { + sb.append(", ") + } + currentNode = currentNode.next + } + + return sb.toString() + } + + fun printList() { + var temp: Node? = head + while (temp != null) { + if(temp.data != null) + println(temp.data) + temp = temp.next + } + } + + private inner class Node(internal var data: T? = null) { + internal var next: Node? = null + internal var previous: Node? = null + } +} + +class DoublyLinkedListTest{ + companion object { + @JvmStatic + fun main(args: Array) { + val ll = DoublyLinkedList() + ll.addHead(11) + ll.addTail(12) + ll.addHead(13) + ll.addTail(8) + ll.addTail(7) + ll.addAtIndex(4, 9) + ll.addAtIndex(4, 9) + ll.deleteAtIndex(4) + ll.printList() + } + } +} diff --git a/data_structures/Linked_list/kotlin/SinglyLinkedList.kt b/data_structures/Linked_list/kotlin/SinglyLinkedList.kt new file mode 100644 index 0000000000..8cf4c89bec --- /dev/null +++ b/data_structures/Linked_list/kotlin/SinglyLinkedList.kt @@ -0,0 +1,103 @@ +/** + * SinglyLinkedListImplementation + */ +class SinglyLinkedList(dat: Any) { + + private var head: Node? = Node(dat) + var size: Int = 0 + + fun addHead(dat: Any) { + val temp = head + head = Node(dat) + head!!.next = temp + size++ + } + + fun addTail(dat: Any) { + var temp = head + while (temp!!.next != null) { + temp = temp.next + } + + temp.next = Node(dat) + size++ + } + + fun addAtIndex(index: Int, dat: Any) { + var temp = head + val holder: Node? + var i = 0 + while (i < index - 1 && temp!!.next != null) { + temp = temp.next + i++ + } + holder = temp!!.next + temp.next = Node(dat) + temp.next!!.next = holder + size++ + } + + fun deleteAtIndex(index: Int) { + var temp = head + var i = 0 + while (i < index - 1 && temp!!.next != null) { + temp = temp.next + i++ + } + temp!!.next = temp.next!!.next + size-- + } + + fun find(n: Node): Int { + var t = head + var index = 0 + while (t !== n) { + index++ + t = t!!.next + } + return index + } + + fun find(index: Int): Node? { + var temp = head + for (i in 0 until index) { + temp = temp!!.next + } + return temp + } + + fun printList() { + var temp = head + while (temp != null) { + println(temp.data) + temp = temp.next + } + } + + inner class Node(val data: Any) { + //Declare class variables + var next: Node? = null + } +} + +/** + * Testing SinglyLinkedList + */ +class TestSinglyLinkedList{ + companion object { + + @JvmStatic + fun main(args: Array) { + val ll = SinglyLinkedList(10) + ll.addHead(11) + ll.addHead(12) + ll.addHead(13) + ll.addTail(8) + ll.addTail(7) + ll.addAtIndex(4, 9) + ll.addAtIndex(4, 9) + ll.deleteAtIndex(4) + ll.printList() + } + } +} \ No newline at end of file diff --git a/data_structures/Linked_list/php/LinkedList.php b/data_structures/Linked_list/php/LinkedList.php new file mode 100644 index 0000000000..b379f9bae3 --- /dev/null +++ b/data_structures/Linked_list/php/LinkedList.php @@ -0,0 +1,104 @@ +find($afterElement); + $newNode = new Node($newElement); + $newNode->next = $node->next; + $newNode->previous = $node; + $node->next = $newNode; + } + + /** + * @param mixed $beforeElement + * @param mixed $newElement + */ + public function insertBefore($beforeElement, $newElement) + { + $node = $this->find($beforeElement); + $newNode = new Node($newElement); + + if (!$node->previous) { + $this->head = $newNode; + } else { + $previousNode = $node->previous; + $previousNode->next = $newNode; + $newNode->previous = $previousNode; + } + + $node->previous = $newNode; + $newNode->next = $node; + } + + /** + * @param mixed $element + */ + public function remove($element) + { + $node = $this->find($element); + + if ($node->previous) { + $node->previous->next = $node->next; + } + + if ($node->next) { + $node->next->previous = $node->previous; + } + } + + /** + * @param $element + * @return Node|null + * @throws \Exception + */ + public function find($element) + { + $currentNode = $this->head; + + while ($currentNode) { + if ($currentNode->element === $element) { + return $currentNode; + } + + $currentNode = $currentNode->next; + + if ($currentNode === $this->head) { + break; + } + }; + + throw new \Exception('Cannot find element.'); + } + + /** + * @return array + */ + public function toArray() + { + $array = []; + + $currentNode = $this->head; + + while ($currentNode) { + $array[] = $currentNode->element; + $currentNode = $currentNode->next; + + if ($currentNode === $this->head) { + break; + } + }; + + return $array; + } +} diff --git a/data_structures/Linked_list/php/Node.php b/data_structures/Linked_list/php/Node.php new file mode 100644 index 0000000000..7ad84b9cc5 --- /dev/null +++ b/data_structures/Linked_list/php/Node.php @@ -0,0 +1,28 @@ +element = $element; + } +} diff --git a/data_structures/Linked_list/php/test.php b/data_structures/Linked_list/php/test.php new file mode 100644 index 0000000000..18b4f710c8 --- /dev/null +++ b/data_structures/Linked_list/php/test.php @@ -0,0 +1,43 @@ +toArray(); + + if ($expected != $array) { + echo sprintf( + 'Invalid list. Expected: %s, got: %s', + print_r($expected, true), + print_r($array, true) + ); + } +} + +$list = new LinkedList(); + +testList([], $list); + +$head = new Node(12); +$list->head = $head; +testList([12], $list); + +$list->insertAfter(12, 99); +testList([12, 99], $list); + +$list->insertAfter(99, 37); +testList([12, 99, 37], $list); + +$list->insertAfter(12, 56); +testList([12, 56, 99, 37], $list); + +$list->insertBefore(56, 100); +testList([12, 100, 56, 99, 37], $list); + +$list->insertBefore(12, 1); +testList([1, 12, 100, 56, 99, 37], $list); + +$list->remove(12); +testList([1, 100, 56, 99, 37], $list); diff --git a/data_structures/Linked_list/rust/Linked_List.rs b/data_structures/Linked_list/rust/Linked_List.rs new file mode 100644 index 0000000000..93165f0a7f --- /dev/null +++ b/data_structures/Linked_list/rust/Linked_List.rs @@ -0,0 +1,45 @@ +use List::{Item, Nil}; + +// linked list implementation in rust + +fn main() { + let mut list = List::new(); + list = list.prepend(1); + list = list.prepend(2); + list = list.prepend(3); + list = list.prepend(4); + + println!("len of final linked list {}", list.len()); + println!("{}", list.stringify()); +} + +enum List { + Item(u32, Box), + Nil, +} + +impl List { + fn new() -> List { + Nil + } + fn prepend(self, elem: u32) -> List { + Item(elem, Box::new(self)) + } + fn len(&self) -> u32 { + match *self { + Item(_, ref tail) => 1 + tail.len(), + Nil => 0 + } + } + fn stringify(&self) -> String { + match *self { + Item(head, ref tail) => { + format!("{}, {}", head, tail.stringify()) + }, + Nil => { + format!("Nil") + } + } + } +} + diff --git a/math/Check_is_square/Java/check_is_square.java b/math/Check_is_square/Java/check_is_square.java new file mode 100644 index 0000000000..3cb1672ac4 --- /dev/null +++ b/math/Check_is_square/Java/check_is_square.java @@ -0,0 +1,22 @@ +public class IsSquare { + + public static void main(String[] args) { + System.out.println("É " + isSquare(4)); + } + + public static boolean isSquare(int num) { + if(num == 1 || num == 0) + return true; + double square = num / 2; + double c = square; + + do { + c = square; + square = (c + (num / c)) / 2; + } while ((c - square) != 0); + + if(square*square == num) + return true; + return false; + } +} diff --git a/math/armstrong_number/Java/ArmstrongNumber.java b/math/armstrong_number/Java/ArmstrongNumber.java new file mode 100644 index 0000000000..4c577e65d3 --- /dev/null +++ b/math/armstrong_number/Java/ArmstrongNumber.java @@ -0,0 +1,30 @@ +import java.util.Scanner; + +public class ArmstrongNumber { + + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + + int num = s.nextInt(); + int toCheck = num; + int toCountDigits = num; + int n = 0; + while (toCountDigits > 0) { + toCountDigits /= 10; + n++; + } + int sum = 0; + while (num > 0) { + int r = num % 10; + sum += Math.pow(r, n); + num /= 10; + } + if (sum == toCheck) { + System.out.println("It is an armstrong number"); + } else { + System.out.println("It is an not armstrong number"); + } + s.close(); + + } +} diff --git a/math/isPalindrome/JavaScript/isPalindrome.js b/math/isPalindrome/JavaScript/isPalindrome.js new file mode 100644 index 0000000000..25b6287ed3 --- /dev/null +++ b/math/isPalindrome/JavaScript/isPalindrome.js @@ -0,0 +1,5 @@ +const isPalindrome = (str) => { + let lowRegStr = str.toLowerCase().replace(/[\W_]/gi, '') + const reverseStr = lowRegStr.split('').reverse().join('') + return reverseStr === lowRegStr +} \ No newline at end of file diff --git a/math/isPalindrome/JavaScript/is_palindrome.js b/math/isPalindrome/JavaScript/is_palindrome.js new file mode 100644 index 0000000000..3ff2f14082 --- /dev/null +++ b/math/isPalindrome/JavaScript/is_palindrome.js @@ -0,0 +1 @@ +const isPalindrome = (value) => value.split('').reverse().join('') === value; diff --git a/math/sieve of eratosthenes/README.md b/math/sieve of eratosthenes/README.md index ecd51331b3..87bf5a71ec 100644 --- a/math/sieve of eratosthenes/README.md +++ b/math/sieve of eratosthenes/README.md @@ -1,12 +1,5 @@ -The 'Sieve of Eratosthenes' is a simple method used to find prime numbers. +# Sieve of Erastothenes +An algorithm used for finding all prime integers less than some positive number n. First create a list of all positive integers from 2 to n. Then, letting p be the first number in the list, repeatedly count up in increments of p and mark each number on that index excluding p itself (2p, 3p, 4p, and so on). p will then take the value of the next unmarked number. After iterating through the whole list, all the numbers that are not marked at the end will be prime. -1 must be left out from this as it is a factor of every number. -So take 2 as prime number. -Then cross of all the integers that are a mutiple of 2. -Then move to the next number that has not been crossed out - 3 -Then cross of all the integers thata re a multiple of 3. - -This must be continued and eventually the prime numbers can be spotted. -This method can be used for finding prime numbers in any range. - -![](https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif) +Illustration: +![Image not available.](https://en.wikipedia.org/wiki/File:Sieve_of_Eratosthenes_animation.gif) diff --git a/sort/bubble_sort/java/Bubblesort.java b/sort/bubble_sort/java/Bubblesort.java index a87d18b6ac..51119815d6 100644 --- a/sort/bubble_sort/java/Bubblesort.java +++ b/sort/bubble_sort/java/Bubblesort.java @@ -1,36 +1,12 @@ -public class BubbleSort { - - static void bubbleSort(int[] arr) { - int n = arr.length; - int temp = 0; - for(int i=0; i < n; i++){ - for(int j=1; j < (n-i); j++){ - if(arr[j-1] > arr[j]){ - //swap elements - temp = arr[j-1]; - arr[j-1] = arr[j]; - arr[j] = temp; - } - - } - } - - } - public static void main(String[] args) { - int arr[] ={3,60,35,2,45,320,5}; - - System.out.println("Array Before Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - System.out.println(); - - bubbleSort(arr);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - - } - } +public static void bubbleSort(int[] ranNum){ + for (int i=0; iranNum[j+1]){ + int temp = ranNum[j+1]; + ranNum[j+1] = ranNum[j]; + ranNum[j] = temp; + } + } + } + System.out.println(Arrays.toString(ranNum)); +} diff --git a/sort/counting_sort/Java/CountingSortTest.java b/sort/counting_sort/Java/CountingSortTest.java new file mode 100644 index 0000000000..5cda3cc270 --- /dev/null +++ b/sort/counting_sort/Java/CountingSortTest.java @@ -0,0 +1,18 @@ + +public class CountingSortTest { + + public static void main(String...args) { + int arr[]= {10,8,9,10,8,7,6,4,4,10,3,2,1,5,4,6,7,9}; + new CountSort().sort(arr); + for(int i=0;iarr[i+1]) + { + System.out.println("Array is not sorted"); + System.exit(1); + } + } + System.out.println("Array is sorted"); + + } +} diff --git a/sort/counting_sort/Java/Counting_sort.java b/sort/counting_sort/Java/Counting_sort.java new file mode 100644 index 0000000000..ec268487a1 --- /dev/null +++ b/sort/counting_sort/Java/Counting_sort.java @@ -0,0 +1,61 @@ +import java.util.*; + +public class CountingSort{ + + public static int[] sort(int[] array) { + + // array to be sorted in, this array is necessary + // when we sort object datatypes, if we don't, + // we can sort directly into the input array + int[] aux = new int[array.length]; + + // find the smallest and the largest value + int min = array[0]; + int max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } else if (array[i] > max) { + max = array[i]; + } + } + + // init array of frequencies + int[] counts = new int[max - min + 1]; + + // init the frequencies + for (int i = 0; i < array.length; i++) { + counts[array[i] - min]++; + } + + // recalculate the array - create the array of occurences + counts[0]--; + for (int i = 1; i < counts.length; i++) { + counts[i] = counts[i] + counts[i-1]; + } + + /* + Sort the array right to the left + 1) Look up in the array of occurences the last occurence of the given value + 2) Place it into the sorted array + 3) Decrement the index of the last occurence of the given value + 4) Continue with the previous value of the input array (goto set1), + terminate if all values were already sorted + */ + for (int i = array.length - 1; i >= 0; i--) { + aux[counts[array[i] - min]--] = array[i]; + } + + return aux; + } + + public static void main(String[] args) { + + int [] unsorted = {5,3,0,2,4,1,0,5,2,3,1,4}; + System.out.println("Before: " + Arrays.toString(unsorted)); + + int [] sorted = sort(unsorted); + System.out.println("After: " + Arrays.toString(sorted)); + + } +} diff --git a/sort/heap_sort/c++/Heap_Sort.cpp b/sort/heap_sort/c++/Heap_Sort.cpp index 92c735d661eaa0b89cc0db085a2e68d4e97497e8..25ba886b28fbf36e9ba404237650eb757e93a6a0 100644 GIT binary patch literal 1345 zcmaJ>$!^;)5Isv@@tOjGoyhf4v^{tM(pwKjfi}0)2S%c-0VL9(s3dOSfA0(_FG+(Q zBvPF1&6`KPCzID*p|K#_dZ$&hO1qZK21Yfy-Kt!p^~F3*$79@DR9bDR+(Du3?%7|% zS?hIyNAeYn#+pQ0WR^)kSA43!h=n<0aqWuuCpt`HKsA3)}@5^XVJ+W4`$KH z(WW|i&C)cHQYAugUQu008=;_sueeWPf|HdP)L3wrmzSZBdW}`wMBwXTnj{CHOVrG5 zpE{O&Gxx#2wJ4Q~RortCgX9y~ zKXu-@mL7DyJ4}$-&`@Qma}fsXWF$gi_g*}bFq66VNQUz?*{Ay;u|}~@%Fg7Ttbw;E zqUO+A=TAEM#b5sjB`Aa;eeGm8QVauDv~$XA7!a>JZmYBoA(VLH24l=H5@8TlOH6nj zjbuQtu@a*UbNXR4?su@f=qK+~&T2K#wQe+vvvjtJnm#MEG$SdnS{~C2w~X|=eb8Y3 zoP>&eq+@LgwjPemw@-10WxS*YSL4Whu-*udZ*za5Hgvi$b6j7Gl#<+b9*aeg5Upi*feRk{;r!ya z;m;_6Te;j@XE#nYslX9U435{I=Xkf~(LGOR8KzTyK4$oo;d6#Bdrlet8Elsyj4efL n!|`c3qgZAlPxlEcj literal 1834 zcmaJ>O;6iE5S^mt6a@k#wgmJe<n`2+W@=k8ljhSzF_N^pft5L;mcX%qmNCIthgdn*5GzxDgC5VxVOK9# zy_n@-leO$Jvf=a`rpVMW -#include +#include -int i,n; +void change_position(int *positionI, int *positionJ){ + int aux; -void input();//function prototype -void display(int b[20]);//function prototype -void sorting(int c[20]);//function prototype - -int main(){ - input(); - return 0; -} - -void input(){ - int a[20]; - printf("Enter the total numbers you want to enter\t"); - scanf("%d",&n); - printf("Enter the numbers you want to enter\t"); - for(i=0;ic[j]){ - temp=c[i]; - c[i]=c[j]; - c[j]=temp; - }//if-close - }//j loop - }//i loop - printf("\nThe result after sorting in ascending order is:\n"); - display(c); - - //selection sorting algorithm for descending order - for(i=0;i<(n-1);i++){ - for(j=i+1;j +#include + +#define size 100 +int stack[size], top = -1; + +void push(int x){ + +if(top > size-1){ + +printf("StackOverflow"); + +}else{ + stack[++top] = x; + printf("Element inserted:%d \n",x); +} + +} +void pop(){ + if(top < 0){ + printf("StackUnderFlow"); + } + else{ + printf("Element deleted %d", stack[top]); + top--; + } + +} +void prints(){ + int i; + printf("Element of stack are:"); + for(i=0; i<=top;i++){ + printf("%d ",stack[i]); + + } + +} + +int main(void){ + + + push(1); + push(2); + push(3); + push(4); + push(5); + push(6); + push(7); + pop(); + prints(); + + return 0; +}