diff --git a/C/Comparator with qsort() b/C/Comparator with qsort() new file mode 100644 index 000000000..44deee3f0 --- /dev/null +++ b/C/Comparator with qsort() @@ -0,0 +1,20 @@ +#include +#include + +int compare(const void *a, const void *b) { + return (*(int*)a - *(int*)b); +} + +int main() { + int arr[] = {7, 2, 9, 5, 3, 8, 1}; + int n = sizeof(arr) / sizeof(arr[0]); + qsort(arr, n, sizeof(int), compare); + + for (int i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + printf("\n"); + + return 0; +} + diff --git a/C/SinglyLinkedList.c b/C/SinglyLinkedList.c new file mode 100644 index 000000000..7d99f5025 --- /dev/null +++ b/C/SinglyLinkedList.c @@ -0,0 +1,75 @@ +#include +#include + +struct Node { + int data; + struct Node* next; +}; + +struct Node* createNode(int data) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = data; + newNode->next = NULL; + return newNode; +} + +void insertAtBeginning(struct Node** head, int data) { + struct Node* newNode = createNode(data); + newNode->next = *head; + *head = newNode; +} + +void insertAtEnd(struct Node** head, int data) { + struct Node* newNode = createNode(data); + if (*head == NULL) { + *head = newNode; + } else { + struct Node* temp = *head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = newNode; + } +} + +void deleteNode(struct Node** head, int key) { + struct Node* temp = *head, *prev = NULL; + if (temp != NULL && temp->data == key) { + *head = temp->next; + free(temp); + return; + } + while (temp != NULL && temp->data != key) { + prev = temp; + temp = temp->next; + } + if (temp == NULL) return; + prev->next = temp->next; + free(temp); +} + +void displayList(struct Node* head) { + while (head != NULL) { + printf("%d -> ", head->data); + head = head->next; + } + printf("NULL\n"); +} + +int main() { + struct Node* head = NULL; + + insertAtBeginning(&head, 10); + insertAtBeginning(&head, 20); + insertAtEnd(&head, 30); + insertAtEnd(&head, 40); + + printf("Linked List: "); + displayList(head); + + deleteNode(&head, 20); + printf("After deletion: "); + displayList(head); + + return 0; +} diff --git a/C/sort_heap.c b/C/sort_heap.c new file mode 100644 index 000000000..9a8b6dabd --- /dev/null +++ b/C/sort_heap.c @@ -0,0 +1,23 @@ +#include +#include +#include +using namespace std; +int main() +{ + vector v = {8, 6, 2, 1, 5, 10}; + + make_heap(v.begin(), v.end()); + + cout << "heap: "; + for (const auto &i : v) { + cout << i << ' '; + } + + sort_heap(v.begin(), v.end()); + + std::cout <