From c9fb0e1a0effd984bac848195fb9626643491fde Mon Sep 17 00:00:00 2001 From: TKushireddy Date: Thu, 16 Nov 2023 20:31:12 +0530 Subject: [PATCH 1/3] codeblogs 1 --- Stack Crud LinkedList/Deque/Easy/Codeblog.md | 275 +++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 Stack Crud LinkedList/Deque/Easy/Codeblog.md diff --git a/Stack Crud LinkedList/Deque/Easy/Codeblog.md b/Stack Crud LinkedList/Deque/Easy/Codeblog.md new file mode 100644 index 00000000..9e8e16c7 --- /dev/null +++ b/Stack Crud LinkedList/Deque/Easy/Codeblog.md @@ -0,0 +1,275 @@ +# Stack CRUD LinkedList + +## Introduction to Stack CRUD LinkedList + +This document delves into the implementation of Stack CRUD (Create, Read, Update, Delete) operations using a LinkedList. A stack is a linear data structure that follows a specific order in which operations are performed. This order can either be LIFO (Last In First Out) or FILO (First In Last Out). On the other hand, a LinkedList is a type of data structure that is a sequence of nodes, with each node connected to the next one through a pointer. Utilizing LinkedLists for stack implementation facilitates dynamic sizes and efficient operations. + +## Overview of Stack CRUD LinkedList + +In a Stack CRUD LinkedList, the stack operations are implemented using a LinkedList. Here, the top of the stack is represented by the head of the LinkedList for efficient O(1) time complexity operations. In this implementation, the 'Create' operation adds a new node to the beginning of the LinkedList, 'Read' operation reads the top element of the stack, 'Update' operation modifies the value of the top node, and 'Delete' operation removes a node from the beginning of the LinkedList. The 'Update' operation is unique to this type of structure as traditional stacks only include Create (Push) and Delete (Pop) operations. + +## Code + +```python +/*copyrights to venkys.io +For more information visit https://venkys.io*/ +// python program to perform Stack CRUD operations on linkedlist +// Stable:No +// Inplace: Yes +// Adaptive:No +// Space complexity: O(n) +// Time complexity:O(1) +#creation of empty linked list +class Node: + def __init__(self,data): + self.data=data + self.next=None +#Stack operations +class StackLL: + def __init__(self): + self.top=None + + # isempty operation on stack + def isempty(self): + return not self.top + # push operation to add element on the top of the stack + def push(self,data): + if not self.top: + self.top=Node(data) + else: + temp=Node(data) + temp.next=self.top + self.top=temp + # pop operation to delete the top elements of the stack + def pop(self): + if self.top: + x=self.top.data + self.top=self.top.next + return x + # traversing the stack + def traverse(self): + head=self.top + while head: + print(head.data,end=" ") + head=head.next + print() + +#providing the inputs to the stack +stack=StackLL() +stack.push(10) +stack.push(20) +stack.push(30) +stack.traverse() +stack.push(40) +stack.push(50) +stack.push(60) +stack.traverse() +stack.pop() +stack.pop() +stack.pop() +stack.traverse() +``` + +## Step-by-Step Explanation + +1. We define a class `Node` which will be used to create new nodes in the LinkedList. Each `Node` consists of data and a `next` pointer. +2. We define a class `StackLL` for the stack, with `top` being the top node in the stack. +3. The `isempty` function checks whether the stack is empty by checking if `top` is None. +4. The `push` function is used to add a new node to the stack. If the stack is empty, the new node becomes `top`. If the stack is not empty, the new node is added to the beginning of the LinkedList and becomes `top`. +5. The `pop` function is used to remove a node from the stack. If the stack is not empty, the node pointed to by `top` is removed and `top` becomes the next node. +6. The `traverse` function is used to print all the elements in the stack from `top` to bottom. +7. Finally, we create an instance of `StackLL` and perform a sequence of `push`, `traverse`, and `pop` operations to demonstrate how the stack works. + +## Code + +```java +/* Copy rights to venkys.io +For more information visit https://venkys.io*/ +// Java program to perform Stack CRUD operations on linkedlist +// Stable:No +// Inplace: Yes +// Adaptive:No +// Space complexity: O(n) +// Time complexity:O(1) +// cration of linked list and initialising a empty node to store data +class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + } +} +// creating a class stack to perform stack operations +class Stack { + Node top; + // push operations helps in adding elements stack linkedlist + void push(int data) { + if (top == null) { + top = new Node(data); + return; + } + Node temp = new Node(data); + temp.next = top; + top = temp; + + } + // pop operations is used in deleting top element from the stack + void pop() { + if (top == null) + return; + top = top.next; + } + // peek operation is used to return the top most element of the stack + void peek() { + if (top == null) + return; + System.out.println(top.data); + } + + void print() { + Node temp = top; + while (temp != null){ + System.out.print(temp.data + " "); + temp=temp.next; + } + System.out.println(); + } +} +// input data to the stack +class Main { + public static void main(String[] args) { + Stack s = new Stack(); + s.push(10); + s.push(20); + s.peek(); + s.print(); + s.pop(); + s.push(30); + s.push(40); + s.peek(); + s.print(); + + } +} + +``` + +## Step-by-Step Explanation + +1. We first define a `Node` class in Java. Each `Node` contains an integer `data` and a `next` field which points to the next node in the stack. +2. We then define a `Stack` class which contains a `Node` `top`, representing the top of the stack. +3. The `push` method is used to add a new node to the stack. If the stack is empty (`top` is null), we create a new `Node` with the given data and set it as `top`. If the stack is not empty, we create a new `Node` with the given data, set its `next` field to the current `top`, and then update `top` to point to the new node. +4. The `pop` method is used to remove the top node from the stack. If the stack is not empty, we simply update `top` to point to the next node. +5. The `peek` method is used to view the data of the top node without removing it from the stack. If the stack is not empty, we print the data of the `top` node. +6. The `print` method is used to print all the data in the stack from top to bottom. +7. Finally, in the `main` method, we create a new `Stack` object and demonstrate the `push`, `peek`, `print`, and `pop` operations. + +## Code +```cpp +/* Copy rights to venkys.io +For more information visit https://venkys.io*/ +// CPP program to perform Stack CRUD operations on linkedlist +// Stable:No +// Inplace: Yes +// Adaptive:No +// Space complexity: O(n) +// Time complexity:O(1) +#include +using namespace std; +/* creating class node for creating linkedlist */ +class VSDnode{ + + public: + int data; + VSDnode* next; + + VSDnode(int val){ + data=val; + next=NULL; +} + +}; +/* push opeartion helps to add new elements to the stack crud linkedlist */ +void VSDpush(VSDnode* &head,int val){ + VSDnode* n= new VSDnode(val); + n->next=head; + head=n; +} +/* pop opeartion helps to delete elements from the stack crud linkedlist */ +void VSDpop(VSDnode* &head){ + if(head==NULL){ + cout<<"stack is empty can't pop"<next; + } +} +void VSDtop(VSDnode* &head){ + cout<<"The top of the stack is : "<data<data<<"->"; + temp=temp->next; + } + cout<<"NULL"< Date: Tue, 9 Jan 2024 21:31:13 +0530 Subject: [PATCH 2/3] updated blogs --- .../LinkedList/Easy/CodeBlogs.md | 611 ++++++++++++++++++ .../Finding loop in linkedlist/codeblogs.md | 520 +++++++++++++++ .../Easy/LinkedListPalindrome/CodeBlogs.md | 341 ++++++++++ Sorting/Hard/Array Heap Sort/Codeblogs.md | 471 ++++++++++++++ Stack Crud LinkedList/Deque/Easy/Codeblog.md | 444 +++++++++---- 5 files changed, 2246 insertions(+), 141 deletions(-) create mode 100644 Doubly Linked List CRUD/LinkedList/Easy/CodeBlogs.md create mode 100644 Linked List/Medium/Finding loop in linkedlist/codeblogs.md create mode 100644 LinkedList/Easy/LinkedListPalindrome/CodeBlogs.md create mode 100644 Sorting/Hard/Array Heap Sort/Codeblogs.md diff --git a/Doubly Linked List CRUD/LinkedList/Easy/CodeBlogs.md b/Doubly Linked List CRUD/LinkedList/Easy/CodeBlogs.md new file mode 100644 index 00000000..cf8a7e47 --- /dev/null +++ b/Doubly Linked List CRUD/LinkedList/Easy/CodeBlogs.md @@ -0,0 +1,611 @@ +# Doubly Linked List CRUD + +## Introduction to Doubly Linked List + +A doubly linked list is a type of data structure that consists of a sequence of nodes, where each node contains a value and two pointers that point to the previous and next nodes in the sequence. Unlike a singly linked list, which only has a pointer to the next node, a doubly linked list allows for traversal in both directions. + +The ability to traverse in both directions makes doubly linked lists useful for certain operations, such as insertion and deletion at both the beginning and end of the list. This flexibility comes at the cost of additional memory required to store the extra pointers. + +In this section, we will explore the basic operations performed on a doubly linked list, including creating a new list, inserting elements, deleting elements, and searching for elements. These operations form the foundation of many more complex algorithms and data structures. + +## Overview of CRUD operations on Doubly Linked List + +### Create + +To create a doubly linked list, we start with an empty list and gradually add elements to it. Each element is inserted at the beginning or end of the list, or at a specific position. + +### Read + +To read elements from a doubly linked list, we can traverse the list starting from either the head or tail node. We can access the value of each node and perform any necessary operations. + +### Update + +To update elements in a doubly linked list, we first need to locate the specific node we want to update. Once we find the node, we can modify its value or any other attributes as needed. + +### Delete + +To delete elements from a doubly linked list, we first need to locate the node we want to remove. Once we find the node, we can update the pointers of the previous and next nodes to bypass the node to be deleted. + +These CRUD operations are fundamental for working with doubly linked lists and allow us to manipulate the data efficiently. + +## Code + +```python +# Copy rights to venkys.io +# Python program to perform CRUD operations on double linkedlist +# Stable:No +# Inplace: Yes +# Adaptive:No +# Space complexity: O(n) +# Time complexity:O(1) +class Node: + def __init__(self, val): + self.prev = None + self.data = val + self.next = None + +class DLL: + def __init__(self): + self.head = None + + # Create Operation: Insert at the Beginning + def insert_begin(self, val): + new_node = Node(val) + if self.head: + self.head.prev = new_node + new_node.next = self.head + self.head = new_node + else: + self.head = new_node + + # Create Operation: Insert at the End + def insert_end(self, val): + new_node = Node(val) + if self.head is None: + self.head = new_node + else: + temp = self.head + while temp.next: + temp = temp.next + new_node.prev = temp + temp.next = new_node + + # Create Operation: Insert at a Specific Position + def insert_pos(self, val, pos): + count = 0 + temp = self.head + while temp: + count += 1 + if count == pos: + break + else: + temp = temp.next + new_node = Node(val) + new_node.prev = temp.prev + new_node.next = temp + temp.prev.next = new_node + + # Delete Operation: Delete from the Beginning + def delete_begin(self): + if self.head is None: + print("List is empty.") + else: + self.head = self.head.next + if self.head: + self.head.prev = None + + # Delete Operation: Delete from the End + def delete_end(self): + if self.head is None: + print("List is empty.") + elif self.head.next is None: + self.head = None + else: + temp = self.head + while temp.next: + temp = temp.next + temp.prev.next = None + + # Delete Operation: Delete from a Specific Position + def delete_pos(self, pos): + count = 0 + temp = self.head + while temp: + count += 1 + if count == pos: + break + else: + temp = temp.next + if temp.next: + temp.next.prev = temp.prev + temp.prev.next = temp.next + else: + temp.prev.next = None + + # Update Operation: Update Node Value + def update(self, pval, nval): + if self.head: + temp = self.head + while temp: + if temp.data == pval: + temp.data = nval + break + temp = temp.next + + # Remove Operation: Remove Node with a Specific Value + def remove(self, val): + if self.head and self.head.data == val: + self.head = self.head.next + if self.head: + self.head.prev = None + else: + temp = self.head + while temp and temp.next: + if temp.data == val: + temp.next.prev = temp.prev + temp.prev.next = temp.next + break + temp = temp.next + + # Display Operation: Display the Doubly Linked List + def display(self): + temp = self.head + while temp: + print(temp.data, end="<->") + temp = temp.next + print("None") + + +# Example Usage +dll = DLL() + +while True: + print("\n1. Insert at the Beginning") + print("2. Insert at the End") + print("3. Insert at a Specific Position") + print("4. Delete from the Beginning") + print("5. Delete from the End") + print("6. Delete from a Specific Position") + print("7. Update Node Value") + print("8. Remove Node with a Specific Value") + print("9. Display") + print("0. Exit") + + choice = int(input("Enter your choice: ")) + + if choice == 1: + val = int(input("Enter value to insert at the beginning: ")) + dll.insert_begin(val) + elif choice == 2: + val = int(input("Enter value to insert at the end: ")) + dll.insert_end(val) + elif choice == 3: + val = int(input("Enter value to insert: ")) + pos = int(input("Enter position to insert at: ")) + dll.insert_pos(val, pos) + elif choice == 4: + dll.delete_begin() + elif choice == 5: + dll.delete_end() + elif choice == 6: + pos = int(input("Enter position to delete: ")) + dll.delete_pos(pos) + elif choice == 7: + pval = int(input("Enter old value to update: ")) + nval = int(input("Enter new value: ")) + dll.update(pval, nval) + elif choice == 8: + val = int(input("Enter value to remove: ")) + dll.remove(val) + elif choice == 9: + dll.display() + elif choice == 0: + print("Exiting...") + break + else: + print("Invalid choice. Please try again.") + +``` + +## Step-by-Step Explanation + +Here is a step-by-step explanation of the linked list program with CRUD operations: + +1. First, we define a **Node** class with attributes for the previous node, data, and the next node. +2. Then, we define a **DLL** (Doubly Linked List) class with a constructor to initialize the head of the list. +3. The **DLL** class contains various methods for the CRUD operations: + - **insert_begin(val)**: Inserts a new node at the beginning of the list. + - **insert_end(val)**: Inserts a new node at the end of the list. + - **insert_pos(val, pos)**: Inserts a new node at a specific position in the list. + - **delete_begin()**: Deletes the node at the beginning of the list. + - **delete_end()**: Deletes the node at the end of the list. + - **delete_pos(pos)**: Deletes the node at a specific position in the list. + - **update(pval, nval)**: Updates the value of a specific node. + - **remove(val)**: Removes a node with the specified value. + - **display()**: Displays the elements of the linked list. +4. The program demonstrates the usage of the linked list methods. +5. The output of each operation is displayed to show the changes in the linked list. +## Test Case 1: +1. Insert 10 +2. Display + Expected Output: 10 +3. Delete +4. Display + Expected Output: (empty) + +## Test Case 2: +1. Insert 5 +2. Insert 8 +3. Insert 12 +4. Display + Expected Output: 12 8 5 +5. Delete +6. Display + Expected Output: 8 5 + +## Test Case 3: +1. Delete + Expected Output: List is empty. Cannot delete. +2. Display + Expected Output: (empty) + +## Code + +```java +// Copy rights to venkys.io +// Java program to perform CRUD operations on double linkedlist +// Stable:No +// Inplace: Yes +// Adaptive:No +// Space complexity: O(n) +// Time complexity:O(1) +import java.util.Scanner; + +class Node { + int data; + Node next; + Node prev; + + Node(int data) { + this.data = data; + } +} + +class DoubleLinkedList { + Node head; + int size = 0; + + // Insertion operation (Create) + void insert(int data) { + if (head == null) { + // If the list is empty, create a new node and set it as the head + head = new Node(data); + } else { + // Otherwise, create a new node, update links, and set it as the new head + Node temp = new Node(data); + temp.next = head; + head.prev = temp; + head = temp; + } + size++; + } + + // Deletion operation (Delete) + void delete() { + if (head == null) { + // If the list is empty, do nothing + System.out.println("List is empty. Cannot delete."); + } else { + // Move the head to the next node, update links, and decrease the size + head = head.next; + if (head != null) { + head.prev = null; + } + size--; + System.out.println("Node deleted successfully."); + } + } + + // Display operation (Read) + void print() { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } + System.out.println(); + } + + // Size operation (Read) + void displaySize() { + System.out.println("Size of the list: " + this.size); + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + DoubleLinkedList doublyLinkedList = new DoubleLinkedList(); + + while (true) { + System.out.println("\nChoose operation:"); + System.out.println("1. Insert"); + System.out.println("2. Delete"); + System.out.println("3. Display"); + System.out.println("4. Display Size"); + System.out.println("5. Exit"); + + int choice = scanner.nextInt(); + + switch (choice) { + case 1: + System.out.println("Enter data to insert:"); + int dataToInsert = scanner.nextInt(); + doublyLinkedList.insert(dataToInsert); + System.out.println("Node inserted successfully."); + break; + + case 2: + doublyLinkedList.delete(); + break; + + case 3: + System.out.println("Elements in the list:"); + doublyLinkedList.print(); + break; + + case 4: + doublyLinkedList.displaySize(); + break; + + case 5: + System.out.println("Exiting the program."); + scanner.close(); + System.exit(0); + + default: + System.out.println("Invalid choice. Please try again."); + } + } + } +} + +``` +## Step-by-Step Explanation + +This program implements a simple double linked list in Java. Below is a step-by-step explanation. + +1. A class **Node** is defined with three properties: **data**, **next**, and **prev**. **data** stores the integer value of the node. **next** and **prev** are pointers to the next and previous nodes, respectively. +2. A class **DoubleLinkedList** is defined with two properties: **head** and **size**. **head** is a pointer to the first node in the list and **size** keeps track of the number of nodes in the list. +3. The **DoubleLinkedList** class has four methods: **insert**, **delete**, **print**, and **size**. + **insert** creates a new node with the given data and adds it to the front of the list. + **delete** removes the node at the front of the list. + **print** prints the data of all nodes in the list from the front to the end. + **size** prints the number of nodes in the list. +4. In the **Main** class, a **DoubleLinkedList** is created and several operations are performed. The list is printed after each operation to show its current state. +## Test Case 1: +1. Insert 10 +2. Display + Expected Output: 10 +3. Delete +4. Display + Expected Output: (empty) + +## Test Case 2: +1. Insert 5 +2. Insert 8 +3. Insert 12 +4. Display + Expected Output: 12 8 5 +5. Delete +6. Display + Expected Output: 8 5 + +## Test Case 3: +1. Delete + Expected Output: List is empty. Cannot delete. +2. Display + Expected Output: (empty) + +## Code +``` +/* Copy rights to venkys.io */ +/* CPP program to perform CRUD operations on double linkedlist*/ +/* Stable:No*/ +/* Inplace: Yes */ +/* Adaptive:No */ +/* Space complexity: O(n) */ +/* Time complexity:O(1) */ +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + Node* prev; + + Node() { + data = 0; + next = NULL; + prev = NULL; + } + + Node(int val) { + data = val; + next = NULL; + prev = NULL; + } +}; + +class DoubleLinkedList { +private: + Node* head = NULL; + int length = 0; + +public: + + /* Insertion operation (Create) */ + void insert(int data) { + if (head == NULL) { + /* If the list is empty, create a new node and set it as the head*/ + head = new Node(data); + } + else { + /* Otherwise, create a new node, update links, and set it as the new head */ + Node* temp = new Node(data); + length++; + temp->next = head; + head->prev = temp; + head = temp; + } + length++; + } + + /* Deletion operation (Delete) */ + void del() { + if (head == NULL) { + cout << "List is empty. Cannot delete.\n"; + return; + } + head = head->next; + if (head != NULL) { + head->prev = NULL; + } + length--; + cout << "Node deleted successfully.\n"; + } + + /* Display operation (Read) */ + void print() { + Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + cout << endl; + } + + /* Size operation (Read)*/ + void displaySize() { + cout << "Size of the list: " << length << endl; + } + + /* Main menu for user interaction */ + void menu() { + int choice, data; + + while (true) { + cout << "\nChoose operation:\n"; + cout << "1. Insert\n"; + cout << "2. Delete\n"; + cout << "3. Display\n"; + cout << "4. Display Size\n"; + cout << "5. Exit\n"; + + cin >> choice; + + switch (choice) { + case 1: + cout << "Enter data to insert: "; + cin >> data; + insert(data); + cout << "Node inserted successfully.\n"; + break; + + case 2: + del(); + break; + + case 3: + cout << "Elements in the list: "; + print(); + break; + + case 4: + displaySize(); + break; + + case 5: + cout << "Exiting the program.\n"; + exit(0); + + default: + cout << "Invalid choice. Please try again.\n"; + } + } + } +}; + +int main() { + DoubleLinkedList doublyLinkedList; + doublyLinkedList.menu(); + + return 0; +} + +``` +## step-by-step Explanation +This program implements a simple double linked list in C++. Here's a step-by-step explanation. +1. A class **Node** is defined with three properties: **data**, **next**, and **prev**. **data** stores the integer value of the node. **next** and **prev** are pointers to the next and previous nodes, respectively. +2. A class **DoubleLinkedList** is defined with two properties: **head** and **length**. **head** is a pointer to the first node in the list, and **length** keeps track of the number of nodes in the list. +3. The **DoubleLinkedList** class has four methods: **insert**, **del**, **print**, and **size**. + **insert** creates a new node with the given data and adds it to the front of the list. + **del** removes the node at the front of the list. + **print** prints the data of all nodes in the list from the front to the end. + *8size** prints the number of nodes in the list. +4. In the **main** function, a **DoubleLinkedList** is created, and several operations are performed. The list is printed after each operation to show its current state. +## Test Case 1: +1. Insert 10 +2. Display + Expected Output: 10 +3. Delete +4. Display + Expected Output: (empty) + +## Test Case 2: +1. Insert 5 +2. Insert 8 +3. Insert 12 +4. Display + Expected Output: 12 8 5 +5. Delete +6. Display + Expected Output: 8 5 + +## Test Case 3: +1. Delete + Expected Output: List is empty. Cannot delete. +2. Display + Expected Output: (empty) +## Time and Space Complexity Analysis + +### Time Complexity + +The time complexity of various operations on a doubly linked list can be analyzed as follows: + +- Insertion at the beginning: O(1) +- Insertion at the end: O(n) +- Insertion at a specific position: O(n) +- Deletion at the beginning: O(1) +- Deletion at the end: O(n) +- Deletion at a specific position: O(n) +- Updating a node: O(n) +- Searching for a node: O(n) + +### Space Complexity + +The space complexity of a doubly linked list depends on the number of nodes in the list. In the worst case, the space complexity is O(n), where n is the number of nodes in the list. + +It's important to note that these time and space complexities are based on the provided implementation. Other implementations may have different time and space complexities. + +Please note that the code provided is in two different programming languages, Python and Java. Each programming language has its own syntax and conventions for implementing doubly linked lists. + +## Real World Applications of Doubly Linked List + +Doubly linked lists have several real-world applications in computer science. Here are a few examples: + +1. **Text Editors**: Doubly linked lists are commonly used to implement text editors. Each character in the text can be represented by a node in the list, and the pointers allow for efficient insertion, deletion, and navigation through the text. +2. **Browser History**: Doubly linked lists are used to implement browser history functionality. Each visited webpage can be stored as a node in the list, and the backward and forward navigation is facilitated by the previous and next pointers. +3. **Undo/Redo Functionality**: Doubly linked lists are useful for implementing undo and redo functionality in applications. Each action performed by the user can be stored as a node in the list, and the pointers allow for traversing back and forth through the actions. +4. **Cache Implementation**: Doubly linked lists are used in cache implementation, such as the LRU (Least Recently Used) cache. The most recently used items are moved to the front of the list, while the least recently used items are moved to the end. This allows for efficient eviction of the least used items when the cache is full. + +These are just a few examples of how doubly linked lists can be used in real-world applications. Their ability to support efficient insertion, deletion, and traversal in both directions makes them a valuable data structure in various scenarios. \ No newline at end of file diff --git a/Linked List/Medium/Finding loop in linkedlist/codeblogs.md b/Linked List/Medium/Finding loop in linkedlist/codeblogs.md new file mode 100644 index 00000000..36274def --- /dev/null +++ b/Linked List/Medium/Finding loop in linkedlist/codeblogs.md @@ -0,0 +1,520 @@ +# Finding Loop In Linked List + +## Introduction to Finding Loop In Linked List + +Finding a loop in a linked list is a common problem in computer science. A loop occurs in a linked list when a node's next pointer points to a previous node in the list, creating a cycle. This can cause issues as some operations might end up in an infinite loop. Various algorithms exist to detect and handle such loops, and understanding these is fundamental to working with linked lists. + +## Overview of Finding Loop In Linked List + +Detecting a loop in a linked list involves traversing the nodes and checking if a node has already been visited or not. There are several methods to solve this problem, including Floyd's cycle-finding algorithm also known as the 'tortoise and the hare' approach. This method uses two pointers moving at different speeds, a slow 'tortoise' pointer and a fast 'hare' pointer. If there's a loop, the fast pointer will eventually meet the slow pointer. If there isn't, the fast pointer will reach the end of the list. Understanding these algorithms is crucial especially when optimizing for performance and efficiency in data structure manipulation. + +## Code + +```python +#Copy rights to venkys.io +#Python program to perform finding loop in linked list +#Stable:Yes +#Inplace: Yes +#Adaptive:No +#Space complexity: O(n) +#Time complexity:O(n) +#loop in a linked list program +class Node: + def __init__(self, val): + self.data = val + self.next = None + +class SLL: + def __init__(self): + self.head = None + + def insert_begin(self, val): + # Insert a new node at the beginning of the linked list + new_node = Node(val) + new_node.next = self.head + self.head = new_node + + def insert_end(self, val): + # Insert a new node at the end of the linked list + new_node = Node(val) + if self.head is None: + self.head = new_node + else: + temp = self.head + while temp.next: + temp = temp.next + temp.next = new_node + + def insert_pos(self, val, pos): + # Insert a new node at a specified position in the linked list + if pos < 1: + print("Invalid position for insertion.") + return + + count = 0 + temp = self.head + while temp: + count += 1 + if count == pos - 1: + break + temp = temp.next + + if temp is None: + print("Invalid position for insertion.") + return + + new_node = Node(val) + new_node.next = temp.next + temp.next = new_node + + def create_loop(self, position, by_value=True): + # Create a loop in the linked list either by value or position + count = 0 + temp = self.head + while temp.next: + count += 1 + if (by_value and count == position) or (not by_value and count == position - 1): + loop_node = temp.next + break + temp = temp.next + + temp.next = loop_node + + def detect_loop(self): + # Detect a loop in the linked list using Floyd's Tortoise and Hare algorithm + slow = self.head + fast = self.head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + print("Loop detected in the linked list.") + return slow # Return the node where the loop starts + + print("No loop found in the linked list.") + return None + + def remove_loop(self): + # Remove the loop in the linked list using Floyd's Tortoise and Hare algorithm + loop_start = self.detect_loop() + if loop_start: + slow = self.head + fast = loop_start + + while slow.next != fast.next: + slow = slow.next + fast = fast.next + + fast.next = None + + def display(self): + # Display the elements of the linked list + temp = self.head + while temp: + print(temp.data, end=" -> ") + temp = temp.next + print("None") + + +# Test drive code with user input: +sll = SLL() + +print("------------INSERTION OPERATIONS-------------") +n = int(input("Enter the number of elements to insert at the beginning: ")) +for _ in range(n): + val = int(input("Enter the value to insert at the beginning: ")) + sll.insert_begin(val) +sll.display() + +n = int(input("Enter the number of elements to insert at the end: ")) +for _ in range(n): + val = int(input("Enter the value to insert at the end: ")) + sll.insert_end(val) +sll.display() + +val = int(input("Enter the value to insert: ")) +pos = int(input("Enter the position to insert at: ")) +sll.insert_pos(val, pos) +sll.display() + +print("------------LOOP CREATION-------------") +pos = int(input("Enter the position for loop creation: ")) +sll.create_loop(pos) +sll.display() + +print("------------LOOP DETECTION-------------") +sll.detect_loop() + +print("------------LOOP REMOVAL-------------") +sll.remove_loop() +sll.display() + +``` + +## Step-by-Step Explanation + +The provided Python code starts by defining a Node class, which represents an individual element in a linked list. Each node contains a value (data) and a pointer to the next node (next). + +The SLL (Singly Linked List) class is defined next. It starts with a head pointer, and includes several methods to manipulate and interact with the linked list, such as: + +- **insert_begin(val)**: This function inserts a new node at the beginning of the list. It creates a new node and points it to the current head of the list. Then, it updates the head of the list to the newly created node. +- **insert_end(val)**: This function inserts a new node at the end of the list. It creates a new node and iterates through the list until it reaches the last node, then adds the new node at the end. +- **insert_pos(val, pos)**: This function inserts a new node at a specified position in the list. It creates a new node, iterates through the list to the specified position, and inserts the new node there. +- **create_loop(val)** and **create_pos_loop(pos)**: These functions create a loop in the list either at a specific value or position, for testing purposes. +- **detect_loop()**: This function uses Floyd's cycle-finding algorithm to detect if a loop exists in the list. It initializes two pointers at the head of the list, then moves them at different speeds (one node at a time for the slow pointer, and two nodes at a time for the fast pointer). If a loop exists in the list, the fast pointer will eventually "lap" the slow pointer and they'll both point to the same node. If there's no loop, the fast pointer will reach the end of the list. +- **remove_loop()**: This function removes a loop from the list if one exists. It uses a similar two-pointer approach to detect the loop, and then resets one of the pointers to the head of the list. It moves both pointers one node at a time until they meet again, at which point it's able to identify and remove the loop. +- **display()**: This function displays the elements of the list from the head to the end, which is helpful for visualizing the list structure. +## Test Case 1: Null Linked List +- Input: +Enter the number of elements in the linked list: 0 +Linked List: +NULL +## Test Case 2: No Cycle +- Input: +Enter the number of elements in the linked list: 5 +Enter the elements of the linked list: +1 2 3 4 5 +Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): 0 +Linked List: 1->2->3->4->5->NULL +No cycle present in the linked list +## Test Case 3: Cycle Present +- Input: +Enter the number of elements in the linked list: 6 +Enter the elements of the linked list: +1 2 3 4 5 6 +Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): 1 +Enter the position to create a cycle: 3 +Linked List: 1->2->3->4->5->6->(cycle starts here) +Cycle present in the linked list + +## Code + +```java +//Copy rights to venkys.io +//Java program to perform finding loop in linked list +//Stable:Yes +//Inplace: Yes +//Adaptive:No +//Space complexity: O(n) +//Time complexity:O(n) +import java.util.*; + +public class VSDFindingLoopInLinkedList { + // Class to hold the structure of a node + private static class VSDNode { + int data; // data of node + VSDNode next; // pointer to next element in the list + + VSDNode(int data) { + this.data = data; + this.next = null; + } + } + + static VSDNode head = null; + + // Function to insert elements into the linked list + public static void VSDinsert(int element) { + VSDNode temp = new VSDNode(element); // creating a new node with the given data + if (head == null) + head = temp; // inserting the first element as head + else { + VSDNode x = head; + while (x.next != null) { + x = x.next; + } + x.next = temp; // inserting node at the end of the linked list + } + } + + // Function to check whether a loop exists in the linked list + public static boolean VSDfindLoop() { + VSDNode slow = head; + VSDNode fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; // Move one step at a time + fast = fast.next.next; // Move two steps at a time + + if (slow == fast) { + return true; // If there is a loop, slow and fast will meet at some point + } + } + return false; + } + + public static void main(String args[]) { + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the number of elements in the linked list:"); + int n = scanner.nextInt(); + + System.out.println("Enter the elements of the linked list:"); + + for (int i = 0; i < n; i++) { + int element = scanner.nextInt(); + VSDinsert(element); + } + + // Asking the user whether to create a loop + System.out.println("Do you want to create a loop in the linked list? (yes/no)"); + String createLoop = scanner.next(); + + if (createLoop.equalsIgnoreCase("yes")) { + // Creating a loop by making the last node point to the head + VSDNode lastNode = head; + while (lastNode.next != null) { + lastNode = lastNode.next; + } + lastNode.next = head; + } + + boolean hasLoop = VSDfindLoop(); + + if (hasLoop) + System.out.println("The linked list contains a loop"); + else + System.out.println("The linked list does not contain a loop"); + + scanner.close(); + } +} +``` + +## Step-by-Step Explanation + +The provided Java code starts by defining a Node class, which represents an individual element in a linked list. Each node contains a value (data) and a pointer to the next node (next). + +The main class, VSDFindingLoopInLinkedList, contains several methods to interact with the linked list: + +- **VSDinsert(int element)**: This function inserts a new node at the end of the list. It creates a temporary node with the provided element, checks if the head of the list is null (which would mean the list is currently empty), and if so, sets the head to the new node. If the list is not empty, it iterates through the list to find the last node, then sets that node's 'next' pointer to the new node. +- **VSDfindLoop()**: This function checks if a loop exists in the list. It creates a HashSet to keep track of the nodes it visits as it iterates through the list. If it encounters a node that is already in the HashSet (which would mean we've visited it before), it returns true, indicating that a loop exists. If it reaches the end of the list without revisiting any nodes, it returns false. + +In the main method, several nodes are inserted into the list using the VSDinsert method, then a loop is manually created for testing purposes by setting the 'next' pointer of one node to the head of the list. The VSDfindLoop method is then called to check for a loop in the list, and the result is printed. + +## Test Case 1: Null Linked List +- Input: +Enter the number of elements in the linked list: 0 +Linked List: +NULL +## Test Case 2: No Cycle +- Input: +Enter the number of elements in the linked list: 5 +Enter the elements of the linked list: +1 2 3 4 5 +Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): 0 +Linked List: 1->2->3->4->5->NULL +No cycle present in the linked list +## Test Case 3: Cycle Present +- Input: +Enter the number of elements in the linked list: 6 +Enter the elements of the linked list: +1 2 3 4 5 6 +Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): 1 +Enter the position to create a cycle: 3 +Linked List: 1->2->3->4->5->6->(cycle starts here) +Cycle present in the linked list + + +## Code + +```cpp +/*Copy rights to venkys.io */ +/*CPP program to perform finding loop in linked list*/ +/*Stable:Yes */ +/*Inplace: Yes */ +/*Adaptive:No */ +/*Space complexity: O(1)*/ +/*Time complexity:O(n)*/ +#include +using namespace std; + +/* Node class definition */ +class VSDnode { +public: + int data; + VSDnode* next; + + VSDnode(int val) { + data = val; + next = NULL; + } +}; + +/* Function to add a node at the head of the linked list */ +void add_head(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + n->next = head; + head = n; +} + +/* Function to add a node at the tail of the linked list */ +void add_tail(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + if (head == NULL) { + head = n; + return; + } + VSDnode* temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = n; +} + +/* Function to create a cycle in the linked list at a specified position */ +void create_cycle_pos(VSDnode* &head, int pos) { + VSDnode* temp = head; + int len = 1; + VSDnode* ptr; + while (temp->next != NULL) { + if (len == pos) { + ptr = temp; + } + temp = temp->next; + len++; + } + temp->next = ptr; +} + +/* Function to detect the presence of a cycle in the linked list using Floyd's Tortoise and Hare algorithm */ +bool detect_cycle(VSDnode* &head) { + VSDnode* slow = head; + VSDnode* fast = head; + while (fast != NULL && fast->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (fast == slow) { + return true; /* Cycle present in the linked list */ + } + } + return false; /* No cycle present in the linked list */ +} + +/* Function to remove the cycle in the linked list */ +void remove_cycle(VSDnode* &head) { + VSDnode* slow = head; + VSDnode* fast = head; + + do { + slow = slow->next; + fast = fast->next->next; + } while (slow != fast); + + fast = head; + while (slow->next != fast->next) { + slow = slow->next; + fast = fast->next; + } + slow->next = NULL; +} + +/* Function to display the linked list */ +void display(VSDnode* head) { + VSDnode* temp = head; + while (temp != NULL) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; +} + +int main() { + VSDnode* head = NULL; + int n; + + cout << "Enter the number of elements in the linked list: "; + cin >> n; + + cout << "Enter the elements of the linked list:" << endl; + for (int i = 0; i < n; i++) { + int element; + cin >> element; + add_tail(head, element); + } + + cout << "Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): "; + int createCycle; + cin >> createCycle; + + if (createCycle) { + cout << "Enter the position to create a cycle: "; + int pos; + cin >> pos; + create_cycle_pos(head, pos); + } + + cout << "Linked List: "; + display(head); + + /* Detecting and displaying whether a cycle is present */ + if (detect_cycle(head)) { + cout << "Cycle present in the linked list" << endl; + remove_cycle(head); + cout << "Linked List after removing the cycle: "; + display(head); + } else { + cout << "No cycle present in the linked list" << endl; + } + + return 0; +} + +``` + +## Step-by-Step Explanation + +The provided C++ code starts by defining a Node class, which represents an individual element in a linked list. Each node contains a value (data) and a pointer to the next node (next). + +The main program contains several functions to interact with the linked list: + +- *add_head(VSDnode &head,int val)*and *add_tail(VSDnode &head,int val)*: These functions insert a new node at the beginning or the end of the list respectively. They create a new node with the provided value and adjust the 'next' pointers accordingly to insert the node at the correct position. +- *create_cycle_pos(VSDnode &head,int pos)*: This function creates a loop in the list for testing purposes. It iterates through the list to the specified position and sets the 'next' pointer of the last node in the list to the node at the specified position, creating a loop. +- *detect_cycle(VSDnode &head)*: This function checks if a loop exists in the list. It uses Floyd's cycle-finding algorithm: it initializes two pointers at the head of the list and moves them at different speeds (one node at a time for the slow pointer, and two nodes at a time for the fast pointer). If a loop exists, the fast pointer will eventually catch up with the slow pointer and they'll point to the same node. If there's no loop, the fast pointer will reach the end of the list. +- *remove_cycle(VSDnode &head)*: This function removes a loop from the list if one exists. It uses a similar two-pointer approach to detect the loop, then resets one of the pointers to the head of the list. It moves both pointers one node at a time until they meet again, then sets the 'next' pointer of the slow pointer to NULL to break the loop. +- *display(VSDnode head)*: This function displays the elements of the list from the head to the end, which is helpful for visualizing the list structure. + +In the main function, several nodes are inserted into the list using the add_head and add_tail functions, a loop is manually created using the create_cycle_pos function, and the detect_cycle function is called to check for a loop in the list. +## Test Case 1: Null Linked List +- Input: +Enter the number of elements in the linked list: 0 +Linked List: +NULL +## Test Case 2: No Cycle +- Input: +Enter the number of elements in the linked list: 5 +Enter the elements of the linked list: +1 2 3 4 5 +Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): 0 +Linked List: 1->2->3->4->5->NULL +No cycle present in the linked list +## Test case 3: Cycle Present +- Input: +Enter the number of elements in the linked list: 6 +Enter the elements of the linked list: +1 2 3 4 5 6 +Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): 1 +Enter the position to create a cycle: 3 +Linked List: 1->2->3->4->5->6->(cycle starts here) +Cycle present in the linked list + + +## Time Complexity: + +For all the languages, the time complexity for detecting and removing loop in a linked list is O(n), where n is the number of nodes in the list. This is because in the worst-case scenario, we traverse all nodes of the list once. + +## Space Complexity: + +The space complexity for the Python and Java implementations is O(n), because we use a HashSet to keep track of visited nodes, which in the worst case will hold all n nodes of the list. + +The space complexity for the C++ implementation is O(1), because it uses Floyd's cycle-finding algorithm with two pointers and does not use any extra space that scales with the size of the input. + +## Real World Applications of Finding Loop In Linked List + +Finding loops in linked lists has several real-world applications: + +1. **Computer Network Troubleshooting:** In computer networks, packets of data are often sent through a series of routers. If there's a loop in the routing, packets could end up circulating indefinitely. Detecting these loops can help identify and correct routing issues. +2. **Operating System:** In operating systems, processes can form a chain where each process is waiting for a resource held by the next process, leading to a deadlock situation. The operating system can detect these loops to avoid deadlock. +3. **Software Debugging:** In software debugging, linked lists are often used to manage software objects. If there's a loop in the linked list, it may result in infinite loops in the software, causing crashes or consuming excessive resources. Detecting these loops can contribute to more robust and efficient software. +4. **Garbage Collection:** In languages that have a garbage collector, such as Java and Python, detecting loops in the object reference graph (which can be thought of as a linked list) makes it possible to identify and deallocate objects that are no longer in use. +5. **Computer Science Education:** Understanding how to find a loop in a linked list is a fundamental concept in computer science education. It helps students understand the concept of data structure and algorithms, which is crucial for problem-solving in coding and programming. \ No newline at end of file diff --git a/LinkedList/Easy/LinkedListPalindrome/CodeBlogs.md b/LinkedList/Easy/LinkedListPalindrome/CodeBlogs.md new file mode 100644 index 00000000..bdf2b053 --- /dev/null +++ b/LinkedList/Easy/LinkedListPalindrome/CodeBlogs.md @@ -0,0 +1,341 @@ +# Linked List Palindrome + +## Introduction to Linked List Palindrome + +A Linked List Palindrome refers to a linked list where the sequence of values in the nodes is the same forwards as it is backwards. This concept is often explored in computer science and data structures. It provides an interesting challenge for algorithm design and can be used to understand and practice various techniques for traversing and analyzing linked lists. + +## Overview of Linked List Palindrome + +A linked list is a data structure in which elements point to the next element in the sequence, forming a chain-like structure. A palindrome is a sequence that reads the same backwards as forwards. Therefore, a linked list palindrome is a linked list that reads the same forwards and backwards. This is usually achieved when the sequence of node values in the linked list is the same when read from the first node to the last, and vice versa. This concept, while simple in theory, can be complex in implementation, and is a common problem presented in computer science and data structures courses. + +## Code + +```python +# Copy rights to venkys.io +# For more information visit https://venkys.io +# Python program to perform Linked List Palindrome +# Stable:Yes +# Inplace:Yes +# Adaptive:No +# Space complexity: O(1) +# Time complexity:O(n) +class Node: + def __init__(self, data): + self.data = data + self.next = None + +def create_list(llist): + head = None + temp = None + for i in llist: + if not temp: + temp = Node(i) + head = temp + else: + temp.next = Node(i) + temp = temp.next + return head + +def check_palindrome(head): + temp = head + stack = [] + + # Push elements of the first half onto the stack + while head: + stack.append(head.data) + head = head.next + + # Compare the second half with the elements popped from the stack + while temp: + if temp.data != stack.pop(): + return False + temp = temp.next + + return True + +if __name__ == "__main__": + # Take user input for the linked list + user_input = input("Enter elements of the linked list separated by spaces: ") + llist = list(map(int, user_input.split())) + + # Create the linked list + head = create_list(llist) + + # Check if the linked list is a palindrome + result = check_palindrome(head) + + # Print the result + if result: + print("The linked list is a palindrome.") + else: + print("The linked list is not a palindrome.") + +``` + +## Step-by-Step Explanation + +1. **Node Class Definition**: The `Node` class is defined with an initializer that takes a data parameter and sets the `next` attribute to `None`. This class will be used to create nodes for the linked list. +2. **Creating the Linked List**: The `createlist` function takes a list as input and creates a linked list from it. It initializes the `head` and `temp` to `None`. Then, for each element in the input list, it creates a new node and updates `temp` to the new node. +3. **Checking for Palindrome**: The `checkpalindrome` function takes the head of the linked list as input and checks if the linked list is a palindrome. It initializes an empty stack and a `temp` variable pointing to the head. Then, it iterates through the linked list, adding each node's data to the stack. Next, it iterates through the linked list again, this time popping elements from the stack and comparing them with the node data. If a node's data does not match the popped stack element, it returns `False`. If it completes the iteration without finding a mismatch, it returns `True`. +4. **Main Function**: In the main function, a list is defined, and the `createlist` function is called with this list to create a linked list. The `checkpalindrome` function is then called with the head of this linked list, and the result is printed. If the linked list is a palindrome, it prints `Plaindrome`; otherwise, `not palindrome`. +## Test Case 1 :Null Linked List +- Input: user_input = "" (Empty string) +- Output: "The linked list is a palindrome." (Since it's an empty list, it is considered a palindrome.) +## Test Case 2 +- Input: user_input = "1 2 3 2 1" +- Output: "The linked list is a palindrome." (The linked list contains a palindrome sequence.) +## Test Case 3 +- Input: user_input = "1 2 3 4 5" +- Output: "The linked list is not a palindrome." (The linked list is not a palindrome as the elements do not read the same backward as forward.) + +## Code + +```java +//Copy rights to venkys.io +//For more information visit https://venkys.io +// Java program to perform Linked List Palindrome +// Stable:Yes +// Inplace:Yes +// Adaptive:No +// Space complexity: O(1) +// Time complexity:O(n) +import java.util.Scanner; +import java.util.Stack; + +class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + } +} + +public class Main { + + // Function to create a linked list from an array of values + static Node createList(int[] values) { + Node head = null, temp = null; + for (int value : values) { + if (temp == null) { + temp = new Node(value); + head = temp; + } else { + temp.next = new Node(value); + temp = temp.next; + } + } + return head; + } + + // Function to check if a linked list is a palindrome + static boolean checkPalindrome(Node head) { + Node temp = head; + Stack stack = new Stack<>(); + + // Push elements of the first half onto the stack + while (head != null) { + stack.push(head.data); + head = head.next; + } + + // Compare the second half with the elements popped from the stack + while (temp != null) { + if (temp.data != stack.pop()) return false; + temp = temp.next; + } + + return true; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Prompt the user to enter values for the linked list + System.out.print("Enter elements of the linked list separated by spaces: "); + String userInput = scanner.nextLine(); + String[] valuesString = userInput.split(" "); + + // Convert the input values to integers + int[] values = new int[valuesString.length]; + for (int i = 0; i < valuesString.length; i++) { + values[i] = Integer.parseInt(valuesString[i]); + } + + // Create the linked list + Node head = createList(values); + + // Check if the linked list is a palindrome + boolean result = checkPalindrome(head); + + // Print the result + if (result) { + System.out.println("The linked list is a palindrome."); + } else { + System.out.println("The linked list is not a palindrome."); + } + } +} + +``` +## Step-by-Step Explanation + +1. **Node Class Definition**: The `Node` class is defined with an initializer that accepts a data parameter. This class is used to create nodes for the linked list. +2. **Creating the Linked List**: The `createList` function takes an array as input and creates a linked list from it. It initializes `head` and `temp` to `null`. Then, for each element in the input array, it creates a new node and updates `temp` to the new node. +3. **Checking for Palindrome**: The `chechPalindrome` function takes the head of the linked list as input and checks if the linked list is a palindrome. It initializes an empty stack and a `temp` variable pointing to the head. Then, it goes through the linked list, adding each node's data to the stack. Next, it goes through the linked list again, this time popping elements from the stack and comparing them with the node data. If a node's data does not match the popped stack element, it returns `false`. If it completes the iteration without finding a mismatch, it returns `true`. +4. **Main Function**: In the main function, an array is defined, and the `createList` function is called with this array to create a linked list. The `chechPalindrome` function is then called with the head of this linked list, and the result is printed. If the linked list is a palindrome, it prints `palindrome`; otherwise, it prints `not palindrome`. +## Test Case 1 :Null Linked List +- Input: user_input = "" (Empty string) +- Output: "The linked list is a palindrome." (Since it's an empty list, it is considered a palindrome.) +## Test Case 2 +- Input: user_input = "1 2 3 2 1" +- Output: "The linked list is a palindrome." (The linked list contains a palindrome sequence.) +## Test Case 3 +- Input: user_input = "1 2 3 4 5" +- Output: "The linked list is not a palindrome." (The linked list is not a palindrome as the elements do not read the same backward as forward.) +## Code + +```cpp +/* Copy rights to venkys.io */ +/* CPP program to perform Linked List Palindrome */ +/* Stable:Yes */ +/* Inplace:Yes */ +/* Adaptive:No */ +/* Space complexity: O(1) */ +/* Time complexity:O(n) */ +#include +using namespace std; + +/* Node class for the linked list */ +class VSDnode { +public: + int data; + VSDnode* next; + + /* Constructor to initialize node with given value */ + VSDnode(int val) { + data = val; + next = NULL; + } +}; + +/* Function to add a new node at the head of the linked list */ +void add_head(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + n->next = head; + head = n; +} + +/* Function to add a new node at the tail of the linked list */ +void add_tail(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + if (head == NULL) { + head = n; + return; + } + VSDnode* temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = n; +} + +/* Function to display the linked list */ +void display(VSDnode* head) { + VSDnode* temp = head; + while (temp != NULL) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; +} + +/* Function to reverse the linked list */ +VSDnode* reverse(VSDnode* head) { + VSDnode* prev = NULL; + VSDnode* curr = head; + + while (curr) { + VSDnode* next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + return prev; +} + +/* Function to check if the linked list is a palindrome */ +void is_palindrome(VSDnode* head) { + VSDnode* new_head = reverse(head); + VSDnode* temp1 = head; + VSDnode* temp2 = new_head; + + while (temp1) { + if (temp1->data != temp2->data) { + cout << "The linked list is not a palindrome" << endl; + return; + } + temp1 = temp1->next; + temp2 = temp2->next; + } + cout << "The linked list is a palindrome" << endl; +} + +int main() { + cout << "Enter the number of elements in the linked list: "; + int n; + cin >> n; + + VSDnode* head = NULL; + + cout << "Enter the elements of the linked list:" << endl; + for (int i = 0; i < n; ++i) { + int val; + cin >> val; + add_tail(head, val); + } + + cout << "Linked List:" << endl; + display(head); + + /* Check if the linked list is a palindrome */ + is_palindrome(head); + + return 0; +} + +``` + +## Step-by-Step Explanation + +1. **Node Class Definition**: The `VSDnode` class is defined with an initializer that accepts a data parameter. This class is used to create nodes for the linked list. +2. **Adding Node to Head**: The `add_head` function takes a head reference and a value as inputs. It creates a new node with the given value and adds it to the head of the linked list. +3. **Adding Node to Tail**: The `add_tail` function takes a head reference and a value as inputs. It creates a new node with the given value and adds it to the tail of the linked list. +4. **Displaying the Linked List**: The `display` function takes the head of the linked list as input and prints the linked list. +5. **Reversing the Linked List**: The `reverse` function takes the head of the linked list as input and returns the head of the reversed linked list. +6. **Checking for Palindrome**: The `is_palindrome` function takes the head of the linked list as input and checks if the linked list is a palindrome. It creates a reversed copy of the linked list and then compares each node in the original and reversed linked lists. If a node's data does not match, it prints "is not a palindrome" and returns. If it completes the iteration without finding a mismatch, it prints "is a palindrome". +7. **Main Function**: In the main function, an empty linked list is created, and nodes are added to the head and tail of the linked list using the `add_head` and `add_tail` functions. The linked list is displayed after each addition. The `is_palindrome` function is called to check if the linked list is a palindrome, and the result is printed. +## Test Case 1 :Null Linked List +- Input: user_input = "" (Empty string) +- Output: "The linked list is a palindrome." (Since it's an empty list, it is considered a palindrome.) +## Test Case 2 +- Input: user_input = "1 2 3 2 1" +- Output: "The linked list is a palindrome." (The linked list contains a palindrome sequence.) +## Test Case 3 +- Input: user_input = "1 2 3 4 5" +- Output: "The linked list is not a palindrome." (The linked list is not a palindrome as the elements do not read the same backward as forward.) + +## Time And Space Complexity Analysis + +- For the **Python** solution, the time complexity of the `checkpalindrome` function is O(n), where n is the number of nodes in the linked list. This is because the function traverses the entire linked list twice: once to push the nodes' data onto the stack, and a second time to check for a palindrome. The space complexity is also O(n) due to the additional stack used to hold the nodes' data. +- For the **Java** solution, the time complexity of the `chechPalindrome` function is also O(n) for the same reasons. The space complexity is also O(n) due to the additional stack used to hold the nodes' data. +- The **C++** solution has a slightly different approach. It creates a reversed copy of the linked list for the palindrome check, so the time complexity remains O(n). However, creating a reversed copy increases the space complexity to O(2n), which simplifies to O(n). Note that this is still considered linear space complexity, but it uses twice as much space as the Python and Java solutions. + +## Real-World Applications of Linked List Palindrome + +Linked List Palindromes, while often seen as an academic or interview question, can have some practical applications in the real world. + +1. **Natural Language Processing**: Palindromes are not limited to numbers or characters, they can also be sequences of words. For example, in natural language processing, or when building a language-based AI model, recognizing palindromes can be an interesting and challenging task. A linked list could be used to store a sequence of words, and then a palindrome algorithm could be used to check if the sequence is the same forwards and backwards. +2. **Genome Sequences**: In bioinformatics, palindromic sequences in DNA or RNA strands, which read the same from 5' to 3' on one strand as they do from 5' to 3' on the complementary strand, play an important role in the formation of various secondary structures in the DNA or RNA molecule. Linked list palindrome algorithms could potentially be adapted to handle this kind of analysis. +3. **Data Transmission**: In computer networks, certain data transmission protocols might involve the sending device appending a special sequence to the end of packets that is the reverse of a sequence at the start of the packets. The receiving device could then use a palindrome checking algorithm to verify that the packet has not been corrupted during transmission. +4. **Error Detection and Correction**: Palindrome properties are also used in error detection and correction techniques. For example, the Longitudinal Redundancy Check (LRC) is a form of parity check that groups bits into sequences, which should be palindromic. If these sequences are not palindromic, an error is detected. \ No newline at end of file diff --git a/Sorting/Hard/Array Heap Sort/Codeblogs.md b/Sorting/Hard/Array Heap Sort/Codeblogs.md new file mode 100644 index 00000000..c1362d0e --- /dev/null +++ b/Sorting/Hard/Array Heap Sort/Codeblogs.md @@ -0,0 +1,471 @@ +# Array Heap Sort + +## Introduction to Array Heap Sort + +Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It divides the input into a sorted and an unsorted region, and iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The heap is updated after each extraction to maintain the heap property. Once all elements have been moved from the unsorted region to the sorted region, the algorithm stops. + +## Overview of Array Heap Sort + +Array Heap Sort is a variant of the Heap Sort algorithm that operates directly on an array. It first transforms the array into a max heap structure, where the maximum heap property is maintained. The maximum element, which is at the root of the heap, is then swapped with the last element of the array, effectively moving it from the unsorted section of the array to the sorted section. The heap size is reduced by one and the max heap property is restored. This process is repeated until all elements in the array are sorted. The advantage of this method is that it does not require any additional space as it sorts in place, making it a space-efficient solution. + +## Code + +```python +#Copy rights to venkys.io +#Python program to perform Array Heap Sort +#Stable:No +#Inplace:Yes +#Adaptive:No +#Space complexity: O(1) +#Time complexity:O(nlogn) +# Function to maintain max heap properties +# Function to maintain max heap properties +def VSDmaxHeapify(arr, size, i): + # Declare current element index as largest element + large = i + + # Find index of left child + leftchild = (2 * i) + 1 + + # Find index of right child + rightchild = (2 * i) + 2 + + # Check largest element between left child and current element + if leftchild < size and arr[i] < arr[leftchild]: + large = leftchild + + # Check largest element between right child and large element + if rightchild < size and arr[large] < arr[rightchild]: + large = rightchild + + # If large element is not the current element + # Swap current element with large element + # Heapify the current array + if large != i: + arr[large], arr[i] = arr[i], arr[large] + VSDmaxHeapify(arr, size, large) + + +# Function to maintain min heap properties +def VSDminHeapify(arr, size, i): + # Declare current element index as smallest + small = i + + # Find index of left child + leftchild = (2 * i) + 1 + + # Find index of right child + rightchild = (2 * i) + 2 + + # Check smallest element between left child and current element + if leftchild < size and arr[i] > arr[leftchild]: + small = leftchild + + # Check smallest element between right child and smallest element + if rightchild < size and arr[small] > arr[rightchild]: + small = rightchild + + # If smallest element is not the current element + # Swap smallest element and current element + # Heapify the current array + if small != i: + arr[small], arr[i] = arr[i], arr[small] + VSDminHeapify(arr, size, small) + + +# Function to insert elements into max heap +def insert(array, num): + if len(array) == 0: + array.append(num) + else: + array.append(num) + for i in range(len(array)): + VSDmaxHeapify(array, len(array), i) + + +# Function to sort the given array using max heap in ascending order +def VSDMaxheapsort(array): + size = len(array) + + # Heapify the given array into max heap + for i in range((size // 2) - 1, -1, -1): + VSDmaxHeapify(array, size, i) + + # Find the max element in array + # Swap the max element with last index element + # Decrease the last index by 1 + # Heapify the current array up to the last index + for i in range(size - 1, 0, -1): + array[i], array[0] = array[0], array[i] + VSDmaxHeapify(array, i, 0) + + +# Function to sort the given array using min heap in descending order +def VSDMinheapsort(array): + size = len(array) + + # Heapify the given array into min heap + for i in range((size // 2) - 1, -1, -1): + VSDminHeapify(array, size, i) + + # Find the min element in array + # Swap the min element with last index element + # Decrease the last index by 1 + # Heapify the current array up to the last index + for i in range(size - 1, -1, -1): + array[0], array[i] = array[i], array[0] + VSDminHeapify(array, i, 0) + + +# Function to print array +def printarray(array): + for i in array: + print(i, end=" ") + print() + + +if __name__ == "__main__": + # Taking user input for the array + user_input = input("Enter numbers separated by spaces: ") + arr = list(map(int, user_input.split())) + + print("Original array:") + printarray(arr) + + # Sorting in ascending order using max heap sort + VSDMaxheapsort(arr) + print("Sorted array in ascending order:") + printarray(arr) + + # Sorting in descending order using min heap sort + VSDMinheapsort(arr) + print("Sorted array in descending order:") + printarray(arr) + +``` + +## Step-by-Step Explanation + +1. The code begins with two functions, `VSDmaxHeapify` and `VSDminHeapify`, which help maintain the max heap and min heap properties, respectively. These functions are used to rearrange the elements of the array such that the parent node is always greater (max heapify) or smaller (min heapify) than its child nodes. +2. The `insert` function is used to insert elements into the max heap. It appends the new element to the end of the array and then rearranges the heap to maintain the max heap property. +3. The `VSDMaxheapsort` function is used to sort the array in ascending order. It first transforms the array into a max heap. Then, it swaps the first element (which is the maximum in a max heap) with the last element of the array, effectively moving it to the sorted section of the array. The size of the heap is then reduced by one and the max heap property is restored. This process is repeated until all elements are sorted. +4. The `VSDMinheapsort` function works similarly to `VSDMaxheapsort`, but it sorts the array in descending order using a min heap. +5. The `printarray` function is used to print the array after it has been sorted. +6. In the main function, an array is defined and then sorted using both `VSDMaxheapsort` and `VSDMinheapsort`. The sorted arrays are then printed to the console. +## Test case 1: +- Enter the elements: 0 +- Expected Output: +Sorted array in ascending order: None +Sorted array in descending order: none +## Test case 2: +- Enter the number of elements: 6 +Enter the elements: 15 7 32 44 9 21 +- Expected Output (Ascending): +Sorted array in ascending order: 7 9 15 21 32 44 +- Expected Output (Descending): +Sorted array in descending order: 44 32 21 15 9 7 +## Code + +```java +//Copy rights to venkys.io +//Java program to perform Array Heap Sort +//Stable:No +//Inplace:Yes +//Adaptive:No +//Space complexity: O(1) +//Time complexity:O(nlogn) +import java.util.Scanner; + +public class Main { + + // Function to swap elements at indices i and j in the array + static void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + // Function to maintain max heap properties + static void VSDmaxheapify(int[] arr, int n, int i) { + int large = i; + int leftChild = 2 * i + 1; + int rightChild = 2 * i + 2; + + if (leftChild < n && arr[i] < arr[leftChild]) { + large = leftChild; + } + + if (rightChild < n && arr[large] < arr[rightChild]) { + large = rightChild; + } + + if (large != i) { + swap(arr, i, large); + VSDmaxheapify(arr, n, large); + } + } + + // Function to maintain min heap properties + static void VSDminheapify(int[] arr, int n, int i) { + int small = i; + int leftChild = 2 * i + 1; + int rightChild = 2 * i + 2; + + if (leftChild < n && arr[i] > arr[leftChild]) { + small = leftChild; + } + + if (rightChild < n && arr[small] > arr[rightChild]) { + small = rightChild; + } + + if (small != i) { + swap(arr, i, small); + VSDminheapify(arr, n, small); + } + } + + // Function to perform max heap sort + static void VSDMaxheapsort(int[] arr) { + int n = arr.length; + + // Build max heap + for (int i = n / 2 - 1; i >= 0; i--) { + VSDmaxheapify(arr, n, i); + } + + // Extract elements one by one + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDmaxheapify(arr, i, 0); + } + } + + // Function to perform min heap sort + static void VSDMinheapsort(int[] arr) { + int n = arr.length; + + // Build min heap + for (int i = n / 2 - 1; i >= 0; i--) { + VSDminheapify(arr, n, i); + } + + // Extract elements one by one + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDminheapify(arr, i, 0); + } + } + + // Function to print array + static void printArray(int[] arr) { + for (int a : arr) { + System.out.print(a + " "); + } + System.out.println(); + } + + public static void main(String args[]) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the number of elements: "); + int n = scanner.nextInt(); + + int[] arr = new int[n]; + + System.out.println("Enter the elements:"); + for (int i = 0; i < n; i++) { + arr[i] = scanner.nextInt(); + } + + System.out.println("Original array:"); + printArray(arr); + + // Sorting in ascending order using max heap sort + VSDMaxheapsort(arr); + System.out.println("Sorted array in ascending order:"); + printArray(arr); + + // Sorting in descending order using min heap sort + VSDMinheapsort(arr); + System.out.println("Sorted array in descending order:"); + printArray(arr); + } +} + +``` + +## Step-by-Step Explanation + +1. The Java code begins with the `swap` function which is used to swap the elements of the array. +2. The `VSDmaxheapify` and `VSDminheapify` functions are used to maintain the max heap and min heap properties respectively. They rearrange the elements of the array such that the parent node is always greater (max heapify) or smaller (min heapify) than its child nodes. +3. `VSDMaxheapsort` function is used to sort the array in ascending order. It first transforms the array into a max heap. Then, it swaps the first element (which is the maximum in a max heap) with the last element of the array, effectively moving it to the sorted section of the array. The size of the heap is then reduced by one and the max heap property is restored. This process is repeated until all elements are sorted. +4. `VSDMinheapsort` function works similarly to `VSDMaxheapsort`, but it sorts the array in descending order using a min heap. +5. The `printarray` function is used to print the array after it has been sorted. +6. In the main function, an array is defined and then sorted using both `VSDMaxheapsort` and `VSDMinheapsort`. The sorted arrays are then printed to the console. +## Test case 1: +- Enter the number of elements: 0 +- Expected Output: +Sorted array in ascending order: None +Sorted array in descending order: none +## Test case 2: +- Enter the number of elements: 6 +Enter the elements: 15 7 32 44 9 21 +- Output (Ascending): +Sorted array in ascending order: 7 9 15 21 32 44 +- Expected Output (Descending): +Sorted array in descending order: 44 32 21 15 9 7 +## Code + +```cpp +/*Copy rights to venkys.io*/ +/*CPP program to perform Array Heap Sort */ +/*Stable:No*/ +/*Inplace:Yes*/ +/*Adaptive:No*/ +/*Space complexity: O(1)*/ +/*Time complexity:O(nlogn)*/ +#include +using namespace std; + +/* Function to swap elements at indices i and j in the array */ +void swap(int arr[], int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + +/* Function to print the elements of an array */ +void printarray(int arr[], int n) { + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + cout << endl; +} + +/* Function to maintain max heap properties*/ +void VSDmaxheapify(int arr[], int n, int i) { + int large = i; + int leftchild = (2 * i) + 1; + int rightchild = (2 * i) + 2; + + if (leftchild < n && arr[i] < arr[leftchild]) + large = leftchild; + if (rightchild < n && arr[large] < arr[rightchild]) + large = rightchild; + if (large != i) { + swap(arr, i, large); + VSDmaxheapify(arr, n, large); + } +} + +/* Function to maintain min heap properties */ +void VSDminheapify(int arr[], int n, int i) { + int small = i; + int leftchild = (2 * i) + 1; + int rightchild = (2 * i) + 2; + + if (leftchild < n && arr[i] > arr[leftchild]) { + small = leftchild; + } + if (rightchild < n && arr[small] > arr[rightchild]) { + small = rightchild; + } + if (small != i) { + swap(arr, small, i); + VSDminheapify(arr, n, small); + } +} + +/* Function to perform max heap sort */ +void VSDMaxheapsort(int arr[], int n) { + /* Build max heap */ + for (int i = (n / 2) - 1; i >= 0; i--) { + VSDmaxheapify(arr, n, i); + } + + /* Extract elements one by one */ + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDmaxheapify(arr, i, 0); + } +} + +/* Function to perform min heap sort */ +void VSDMinheapsort(int arr[], int n) { + /* Build min heap */ + for (int i = (n / 2) - 1; i >= 0; i--) { + VSDminheapify(arr, n, i); + } + + /* Extract elements one by one */ + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDminheapify(arr, i, 0); + } +} + +int main() { + /* Taking user input for the number of elements */ + cout << "Enter the number of elements: "; + int n; + cin >> n; + + /* Taking user input for the array */ + int arr[n]; + cout << "Enter the elements: "; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + /* Sorting in ascending order using max heap sort */ + VSDMaxheapsort(arr, n); + cout << "Sorted array in ascending order: "; + printarray(arr, n); + + /* Sorting in descending order using min heap sort */ + VSDMinheapsort(arr, n); + cout << "Sorted array in descending order: "; + printarray(arr, n); + + return 0; +} + +``` + +## Step-by-Step Explanation + +1. The C++ code starts with the `swap` function which is used to interchange the elements of the array. +2. The `VSDmaxheapify` and `VSDminheapify` functions are used to maintain the max heap and min heap properties respectively. They rearrange the elements of the array such that the parent node is always greater (max heapify) or smaller (min heapify) than its child nodes. +3. `VSDMaxheapsort` function is used to sort the array in ascending order. It first transforms the array into a max heap. Then, it swaps the first element (which is the maximum in a max heap) with the last element of the array, effectively moving it to the sorted section of the array. The size of the heap is then reduced by one and the max heap property is restored. This process is repeated until all elements are sorted. +4. `VSDMinheapsort` function works similarly to `VSDMaxheapsort`, but it sorts the array in descending order using a min heap. +5. The `printarray` function is used to print the array after it has been sorted. +6. In the main function, an array is defined and then sorted using both `VSDMaxheapsort` and `VSDMinheapsort`. The sorted arrays are then printed to the console. +## Test case 1: +- Enter the number of elements: 0 +- Expected Output: +Sorted array in ascending order: None +Sorted array in descending order: none +## Test case 2: +- Enter the number of elements: 6 +Enter the elements: 15 7 32 44 9 21 +- Expected Output (Ascending): +Sorted array in ascending order: 7 9 15 21 32 44 +- Expected Output (Descending): +Sorted array in descending order: 44 32 21 15 9 7 + +## Time And Space Complexity Analysis + +Heap Sort has a time complexity of O(n log n) for both the best case and the worst case. This is because it takes O(log n) time to heapify each of the n elements in the array. + +The space complexity of Heap Sort is O(1). This is one of the main advantages of Heap Sort, especially the Array Heap Sort variant. Array Heap Sort operates directly on the array and does not require any additional space, making it a very space-efficient sorting algorithm. + +## Real World Applications of Array Heap Sort + +Heap sort, including the variant of Array Heap Sort, is used in a wide range of applications due to its efficiency, including: + +1. Database systems: Heap Sort is widely used in database systems for sorting large datasets. It's particularly effective when used in conjunction with a binary heap data structure. +2. Priority Queues: Heap Sort is used in priority queues, which are used in scheduling processes in operating systems. +3. Graph Algorithms: Heap Sort is used in graph algorithms such as Dijkstra’s algorithm and Prim’s algorithm to find the shortest path and minimum spanning tree, respectively. +4. Selection Algorithm: The Heap Sort algorithm can be used to find the kth smallest or largest number in an array. +5. Space-restricted scenarios: Given its in-place sorting nature, Heap Sort is also beneficial in scenarios where memory space is a significant constraint. \ No newline at end of file diff --git a/Stack Crud LinkedList/Deque/Easy/Codeblog.md b/Stack Crud LinkedList/Deque/Easy/Codeblog.md index 9e8e16c7..e3c1d122 100644 --- a/Stack Crud LinkedList/Deque/Easy/Codeblog.md +++ b/Stack Crud LinkedList/Deque/Easy/Codeblog.md @@ -11,63 +11,80 @@ In a Stack CRUD LinkedList, the stack operations are implemented using a LinkedL ## Code ```python -/*copyrights to venkys.io -For more information visit https://venkys.io*/ -// python program to perform Stack CRUD operations on linkedlist -// Stable:No -// Inplace: Yes -// Adaptive:No -// Space complexity: O(n) -// Time complexity:O(1) -#creation of empty linked list +#copyrights to venkys.io +#python program to perform Stack CRUD operations on linkedlist +#Stable:No +#Inplace: Yes +#Adaptive:No +#Space complexity: O(n) +#Time complexity:O(1) class Node: - def __init__(self,data): - self.data=data - self.next=None -#Stack operations + def __init__(self, data): + self.data = data + self.next = None + class StackLL: def __init__(self): - self.top=None + self.top = None - # isempty operation on stack def isempty(self): - return not self.top - # push operation to add element on the top of the stack - def push(self,data): + #Check if the stack is empty.# + return not self.top + + def push(self, data): + #Push a new element onto the stack. if not self.top: - self.top=Node(data) + self.top = Node(data) else: - temp=Node(data) - temp.next=self.top - self.top=temp - # pop operation to delete the top elements of the stack + temp = Node(data) + temp.next = self.top + self.top = temp + def pop(self): + #Pop the top element from the stack and return its value. if self.top: - x=self.top.data - self.top=self.top.next + x = self.top.data + self.top = self.top.next return x - # traversing the stack + else: + print("Stack is empty. Cannot pop.") + def traverse(self): - head=self.top + #Traverse and print the elements in the stack. + head = self.top while head: - print(head.data,end=" ") - head=head.next + print(head.data, end=" ") + head = head.next print() - -#providing the inputs to the stack -stack=StackLL() -stack.push(10) -stack.push(20) -stack.push(30) -stack.traverse() -stack.push(40) -stack.push(50) -stack.push(60) -stack.traverse() -stack.pop() -stack.pop() -stack.pop() -stack.traverse() +# Create an instance of StackLL +stack = StackLL() +while True: + print("\nSelect stack operation:") + print("1. Push") + print("2. Pop") + print("3. Display") + print("4. Exit") + + choice = input("Enter choice (1/2/3/4): ") + + if choice == '1': + data = input("Enter data to push onto the stack: ") + stack.push(data) + print(f"{data} pushed onto the stack.") + elif choice == '2': + popped_element = stack.pop() + if popped_element is not None: + print(f"Popped element: {popped_element}") + elif choice == '3': + print("Stack elements:") + stack.traverse() + elif choice == '4': + print("Exiting the program.") + break + else: + print("Invalid choice. Please enter a valid option.") + + ``` ## Step-by-Step Explanation @@ -78,20 +95,45 @@ stack.traverse() 4. The `push` function is used to add a new node to the stack. If the stack is empty, the new node becomes `top`. If the stack is not empty, the new node is added to the beginning of the LinkedList and becomes `top`. 5. The `pop` function is used to remove a node from the stack. If the stack is not empty, the node pointed to by `top` is removed and `top` becomes the next node. 6. The `traverse` function is used to print all the elements in the stack from `top` to bottom. -7. Finally, we create an instance of `StackLL` and perform a sequence of `push`, `traverse`, and `pop` operations to demonstrate how the stack works. +7. Finally, we create an instance of `StackLL` and perform a sequence of `push`, `traverse`, and `pop` operations to demonstrate how the stack works based on the user choice using while loop. + +## Test Case 1: Empty Stack (null) +- Input: +Choose option 4 (Display) when the stack is empty. +- Expected Output: +The program should print "Stack is empty" as there are no elements in the stack. +## Test Case 2: Push and Pop Operations (true) +- Input: +Choose option 1 (Push) and enter the value 42. +Choose option 1 (Push) and enter the value 17. +Choose option 2 (Pop) to remove the top element. +Choose option 4 (Display) to show the elements. +- Expected Output: +The program should print: +arduino +Copy code +42 pushed onto the stack. +17 pushed onto the stack. +17 popped from the stack. +42-> +## Test Case 3: Top Operation on Empty Stack (false) +- Input: +Choose option 3 (Top) when the stack is empty. +- Expected Output: +The program should print "Stack is empty. Cannot get top." since there are no elements in the stack, and it cannot retrieve the top element. ## Code ```java -/* Copy rights to venkys.io -For more information visit https://venkys.io*/ +// Copy rights to venkys.io // Java program to perform Stack CRUD operations on linkedlist // Stable:No // Inplace: Yes // Adaptive:No // Space complexity: O(n) // Time complexity:O(1) -// cration of linked list and initialising a empty node to store data +import java.util.Scanner; + class Node { int data; Node next; @@ -100,56 +142,97 @@ class Node { this.data = data; } } -// creating a class stack to perform stack operations + class Stack { Node top; - // push operations helps in adding elements stack linkedlist + + // Push operation: Add a new node with the specified data to the top of the stack. void push(int data) { if (top == null) { + // If the stack is empty, create the first node. top = new Node(data); - return; + } else { + // If the stack is not empty, create a new node and update the top. + Node temp = new Node(data); + temp.next = top; + top = temp; } - Node temp = new Node(data); - temp.next = top; - top = temp; - } - // pop operations is used in deleting top element from the stack + + // Pop operation: Remove the top node from the stack. void pop() { - if (top == null) - return; - top = top.next; + if (top != null) { + // If the stack is not empty, update the top to the next node. + top = top.next; + } } - // peek operation is used to return the top most element of the stack + + // Peek operation: Print the data of the top node without removing it. void peek() { - if (top == null) - return; - System.out.println(top.data); + if (top != null) { + // If the stack is not empty, print the data of the top node. + System.out.println("Peek: " + top.data); + } } - void print() { - Node temp = top; - while (temp != null){ + // Recursive print method: Print all elements in the stack from top to bottom. + void printRecursive(Node temp) { + if (temp != null) { + printRecursive(temp.next); System.out.print(temp.data + " "); - temp=temp.next; } - System.out.println(); + } + + // Print operation: Print all the elements in the stack from top to bottom. + void print() { + if (top != null) { + System.out.print("Stack elements: "); + // Call the recursive print method to print elements. + printRecursive(top); + System.out.println(); + } } } -// input data to the stack -class Main { + +public class Main { public static void main(String[] args) { - Stack s = new Stack(); - s.push(10); - s.push(20); - s.peek(); - s.print(); - s.pop(); - s.push(30); - s.push(40); - s.peek(); - s.print(); + Scanner scanner = new Scanner(System.in); + Stack stack = new Stack(); + while (true) { + System.out.println("\nChoose an operation:"); + System.out.println("1. Push"); + System.out.println("2. Pop"); + System.out.println("3. Peek"); + System.out.println("4. Print"); + System.out.println("5. Exit"); + + int choice = scanner.nextInt(); + + switch (choice) { + case 1: + System.out.println("Enter the value to push:"); + int pushValue = scanner.nextInt(); + stack.push(pushValue); + break; + case 2: + stack.pop(); + break; + case 3: + stack.peek(); + break; + case 4: + stack.print(); + break; + case 5: + System.out.println("Exiting the program."); + scanner.close(); + System.exit(0); + break; + default: + System.out.println("Invalid choice. Please try again."); + } + } } } @@ -163,81 +246,135 @@ class Main { 4. The `pop` method is used to remove the top node from the stack. If the stack is not empty, we simply update `top` to point to the next node. 5. The `peek` method is used to view the data of the top node without removing it from the stack. If the stack is not empty, we print the data of the `top` node. 6. The `print` method is used to print all the data in the stack from top to bottom. -7. Finally, in the `main` method, we create a new `Stack` object and demonstrate the `push`, `peek`, `print`, and `pop` operations. +7. Finally, in the `main` method, we create a new `Stack` object and demonstrate the `push`, `peek`, `print`, and `pop` operations are performed based on user choice using while loop. +## Test Case 1: Empty Stack (null) +- Input: +Choose option 4 (Display) when the stack is empty. +- Expected Output: +The program should print "Stack is empty" as there are no elements in the stack. +## Test Case 2: Push and Pop Operations (true) +- Input: +Choose option 1 (Push) and enter the value 42. +Choose option 1 (Push) and enter the value 17. +Choose option 2 (Pop) to remove the top element. +Choose option 4 (Display) to show the elements. +- Expected Output: +The program should print: +arduino +Copy code +42 pushed onto the stack. +17 pushed onto the stack. +17 popped from the stack. +42-> +## Test Case 3: Top Operation on Empty Stack (false) +- Input: +Choose option 3 (Top) when the stack is empty. +- Expected Output: +The program should print "Stack is empty. Cannot get top." since there are no elements in the stack, and it cannot retrieve the top element. + ## Code ```cpp -/* Copy rights to venkys.io -For more information visit https://venkys.io*/ -// CPP program to perform Stack CRUD operations on linkedlist -// Stable:No -// Inplace: Yes -// Adaptive:No -// Space complexity: O(n) -// Time complexity:O(1) +/* Copy rights to venkys.io */ +/* CPP program to perform Stack CRUD operations on linkedlist*/ +/* Stable:No */ +/* Inplace: Yes*/ +/* Adaptive:No*/ +/* Space complexity: O(n)*/ +/* Time complexity:O(1) */ #include using namespace std; -/* creating class node for creating linkedlist */ -class VSDnode{ - - public: - int data; - VSDnode* next; - - VSDnode(int val){ - data=val; - next=NULL; -} +class VSDnode { +public: + int data; + VSDnode* next; + + VSDnode(int val) { + data = val; + next = NULL; + } }; -/* push opeartion helps to add new elements to the stack crud linkedlist */ -void VSDpush(VSDnode* &head,int val){ - VSDnode* n= new VSDnode(val); - n->next=head; - head=n; + +/* Function to push a new element onto the stack*/ +void VSDpush(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + n->next = head; + head = n; } -/* pop opeartion helps to delete elements from the stack crud linkedlist */ -void VSDpop(VSDnode* &head){ - if(head==NULL){ - cout<<"stack is empty can't pop"<next; - } + +/* Function to pop the top element from the stack */ +void VSDpop(VSDnode* &head) { + if (head == NULL) { + cout << "Stack is empty. Cannot pop." << endl; + } else { + head = head->next; + } } -void VSDtop(VSDnode* &head){ - cout<<"The top of the stack is : "<data<data << endl; + } else { + cout << "Stack is empty. Cannot get top." << endl; + } } -void VSDdisplay(VSDnode* head){ - - VSDnode* temp=head; - while(temp!=NULL){ - cout<data<<"->"; - temp=temp->next; - } - cout<<"NULL"<data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; } -/* all the opeartions output are diaplayed here which are performed on stack crud linkedlist */ + int main() { - cout<<"-----empty stack created-----"<> choice; + + switch (choice) { + case 1: { + int val; + cout << "Enter the value to push onto the stack: "; + cin >> val; + VSDpush(head, val); + cout << val << " pushed onto the stack." << endl; + break; + } + case 2: + VSDpop(head); + break; + case 3: + VSDtop(head); + break; + case 4: + VSDdisplay(head); + break; + case 5: + cout << "Quitting the program." << endl; + return 0; + default: + cout << "Invalid choice. Please enter 1, 2, 3, 4, or 5." << endl; + } + } + return 0; } + ``` ## Step-by-Step Explanation @@ -246,7 +383,32 @@ int main() { 3. The `VSDpop` function removes the top node from the stack. If the stack is not empty, it simply sets the `next` node of the current top node as the new top of the stack. 4. The `VSDtop` function displays the value of the top node of the stack. 5. The `VSDdisplay` function traverses the stack from top to bottom and prints all the nodes. -6. Finally, in the `main` function, a new stack is created and the `VSDpush`, `VSDpop`, `VSDtop`, and `VSDdisplay` operations are demonstrated. +6. Finally, in the `main` function, a new stack is created and the `VSDpush`, `VSDpop`, `VSDtop`, and `VSDdisplay` operations are demonstrated using switch case based on users choice. +## Test Case 1: Empty Stack (null) +- Input: +Choose option 4 (Display) when the stack is empty. +- Expected Output: +The program should print "Stack is empty" as there are no elements in the stack. +## Test Case 2: Push and Pop Operations (true) +- Input: +Choose option 1 (Push) and enter the value 42. +Choose option 1 (Push) and enter the value 17. +Choose option 2 (Pop) to remove the top element. +Choose option 4 (Display) to show the elements. +- Expected Output: +The program should print: +arduino +Copy code +42 pushed onto the stack. +17 pushed onto the stack. +17 popped from the stack. +42-> +## Test Case 3: Top Operation on Empty Stack (false) +- Input: +Choose option 3 (Top) when the stack is empty. +- Expected Output: +The program should print "Stack is empty. Cannot get top." since there are no elements in the stack, and it cannot retrieve the top element. + ## Time and Space Complexity Analysis From 4e77885ee1be035b4768c6c73014f37c83b7f7dd Mon Sep 17 00:00:00 2001 From: TKushireddy Date: Fri, 12 Jan 2024 22:57:31 +0530 Subject: [PATCH 3/3] changes --- .../LinkedList/Easy/DoubleLinkedlist.py | 166 ++++++++++++++++++ .../LinkedList/Easy/LinkedList.cpp | 127 ++++++++++++++ .../LinkedList/Easy/LinkedList.java | 108 ++++++++++++ .../FindingLoop.cpp | 133 ++++++++++++++ .../Finding loop in linkedlist/Findingloop.py | 129 ++++++++++++++ .../VSDFindingLoopInLinkedList.java | 83 +++++++++ .../Easy/LinkedListPalindrome/Main.java | 77 ++++++++ .../Easy/LinkedListPalindrome/palindrome.cpp | 100 +++++++++++ .../Easy/LinkedListPalindrome/palindrome.py | 50 ++++++ Sorting/Hard/Array Heap Sort/Main.java | 118 +++++++++++++ Sorting/Hard/Array Heap Sort/sort.cpp | 105 +++++++++++ Sorting/Hard/Array Heap Sort/sort.py | 123 +++++++++++++ Stack Crud LinkedList/Deque/Easy/Stack.java | 104 +++++++++++ Stack Crud LinkedList/Deque/Easy/stack.cpp | 92 ++++++++++ Stack Crud LinkedList/Deque/Easy/stack.py | 65 +++++++ 15 files changed, 1580 insertions(+) create mode 100644 Doubly Linked List CRUD/LinkedList/Easy/DoubleLinkedlist.py create mode 100644 Doubly Linked List CRUD/LinkedList/Easy/LinkedList.cpp create mode 100644 Doubly Linked List CRUD/LinkedList/Easy/LinkedList.java create mode 100644 Linked List/Medium/Finding loop in linkedlist/FindingLoop.cpp create mode 100644 Linked List/Medium/Finding loop in linkedlist/Findingloop.py create mode 100644 Linked List/Medium/Finding loop in linkedlist/VSDFindingLoopInLinkedList.java create mode 100644 LinkedList/Easy/LinkedListPalindrome/Main.java create mode 100644 LinkedList/Easy/LinkedListPalindrome/palindrome.cpp create mode 100644 LinkedList/Easy/LinkedListPalindrome/palindrome.py create mode 100644 Sorting/Hard/Array Heap Sort/Main.java create mode 100644 Sorting/Hard/Array Heap Sort/sort.cpp create mode 100644 Sorting/Hard/Array Heap Sort/sort.py create mode 100644 Stack Crud LinkedList/Deque/Easy/Stack.java create mode 100644 Stack Crud LinkedList/Deque/Easy/stack.cpp create mode 100644 Stack Crud LinkedList/Deque/Easy/stack.py diff --git a/Doubly Linked List CRUD/LinkedList/Easy/DoubleLinkedlist.py b/Doubly Linked List CRUD/LinkedList/Easy/DoubleLinkedlist.py new file mode 100644 index 00000000..a3c9c7dc --- /dev/null +++ b/Doubly Linked List CRUD/LinkedList/Easy/DoubleLinkedlist.py @@ -0,0 +1,166 @@ +class Node: + def __init__(self, val): + self.prev = None + self.data = val + self.next = None + +class DLL: + def __init__(self): + self.head = None + + # Create Operation: Insert at the Beginning + def insert_begin(self, val): + new_node = Node(val) + if self.head: + self.head.prev = new_node + new_node.next = self.head + self.head = new_node + else: + self.head = new_node + + # Create Operation: Insert at the End + def insert_end(self, val): + new_node = Node(val) + if self.head is None: + self.head = new_node + else: + temp = self.head + while temp.next: + temp = temp.next + new_node.prev = temp + temp.next = new_node + + # Create Operation: Insert at a Specific Position + def insert_pos(self, val, pos): + count = 0 + temp = self.head + while temp: + count += 1 + if count == pos: + break + else: + temp = temp.next + new_node = Node(val) + new_node.prev = temp.prev + new_node.next = temp + temp.prev.next = new_node + + # Delete Operation: Delete from the Beginning + def delete_begin(self): + if self.head is None: + print("List is empty.") + else: + self.head = self.head.next + if self.head: + self.head.prev = None + + # Delete Operation: Delete from the End + def delete_end(self): + if self.head is None: + print("List is empty.") + elif self.head.next is None: + self.head = None + else: + temp = self.head + while temp.next: + temp = temp.next + temp.prev.next = None + + # Delete Operation: Delete from a Specific Position + def delete_pos(self, pos): + count = 0 + temp = self.head + while temp: + count += 1 + if count == pos: + break + else: + temp = temp.next + if temp.next: + temp.next.prev = temp.prev + temp.prev.next = temp.next + else: + temp.prev.next = None + + # Update Operation: Update Node Value + def update(self, pval, nval): + if self.head: + temp = self.head + while temp: + if temp.data == pval: + temp.data = nval + break + temp = temp.next + + # Remove Operation: Remove Node with a Specific Value + def remove(self, val): + if self.head and self.head.data == val: + self.head = self.head.next + if self.head: + self.head.prev = None + else: + temp = self.head + while temp and temp.next: + if temp.data == val: + temp.next.prev = temp.prev + temp.prev.next = temp.next + break + temp = temp.next + + # Display Operation: Display the Doubly Linked List + def display(self): + temp = self.head + while temp: + print(temp.data, end="<->") + temp = temp.next + print("None") + + +# Example Usage +dll = DLL() + +while True: + print("\n1. Insert at the Beginning") + print("2. Insert at the End") + print("3. Insert at a Specific Position") + print("4. Delete from the Beginning") + print("5. Delete from the End") + print("6. Delete from a Specific Position") + print("7. Update Node Value") + print("8. Remove Node with a Specific Value") + print("9. Display") + print("0. Exit") + + choice = int(input("Enter your choice: ")) + + if choice == 1: + val = int(input("Enter value to insert at the beginning: ")) + dll.insert_begin(val) + elif choice == 2: + val = int(input("Enter value to insert at the end: ")) + dll.insert_end(val) + elif choice == 3: + val = int(input("Enter value to insert: ")) + pos = int(input("Enter position to insert at: ")) + dll.insert_pos(val, pos) + elif choice == 4: + dll.delete_begin() + elif choice == 5: + dll.delete_end() + elif choice == 6: + pos = int(input("Enter position to delete: ")) + dll.delete_pos(pos) + elif choice == 7: + pval = int(input("Enter old value to update: ")) + nval = int(input("Enter new value: ")) + dll.update(pval, nval) + elif choice == 8: + val = int(input("Enter value to remove: ")) + dll.remove(val) + elif choice == 9: + dll.display() + elif choice == 0: + print("Exiting...") + break + else: + print("Invalid choice. Please try again.") \ No newline at end of file diff --git a/Doubly Linked List CRUD/LinkedList/Easy/LinkedList.cpp b/Doubly Linked List CRUD/LinkedList/Easy/LinkedList.cpp new file mode 100644 index 00000000..a131b0e6 --- /dev/null +++ b/Doubly Linked List CRUD/LinkedList/Easy/LinkedList.cpp @@ -0,0 +1,127 @@ +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + Node* prev; + + Node() { + data = 0; + next = NULL; + prev = NULL; + } + + Node(int val) { + data = val; + next = NULL; + prev = NULL; + } +}; + +class DoubleLinkedList { +private: + Node* head = NULL; + int length = 0; + +public: + + /* Insertion operation (Create) */ + void insert(int data) { + if (head == NULL) { + /* If the list is empty, create a new node and set it as the head*/ + head = new Node(data); + } + else { + /* Otherwise, create a new node, update links, and set it as the new head */ + Node* temp = new Node(data); + length++; + temp->next = head; + head->prev = temp; + head = temp; + } + length++; + } + + /* Deletion operation (Delete) */ + void del() { + if (head == NULL) { + cout << "List is empty. Cannot delete.\n"; + return; + } + head = head->next; + if (head != NULL) { + head->prev = NULL; + } + length--; + cout << "Node deleted successfully.\n"; + } + + /* Display operation (Read) */ + void print() { + Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + cout << endl; + } + + /* Size operation (Read)*/ + void displaySize() { + cout << "Size of the list: " << length << endl; + } + + /* Main menu for user interaction */ + void menu() { + int choice, data; + + while (true) { + cout << "\nChoose operation:\n"; + cout << "1. Insert\n"; + cout << "2. Delete\n"; + cout << "3. Display\n"; + cout << "4. Display Size\n"; + cout << "5. Exit\n"; + + cin >> choice; + + switch (choice) { + case 1: + cout << "Enter data to insert: "; + cin >> data; + insert(data); + cout << "Node inserted successfully.\n"; + break; + + case 2: + del(); + break; + + case 3: + cout << "Elements in the list: "; + print(); + break; + + case 4: + displaySize(); + break; + + case 5: + cout << "Exiting the program.\n"; + exit(0); + + default: + cout << "Invalid choice. Please try again.\n"; + } + } + } +}; + +int main() { + DoubleLinkedList doublyLinkedList; + doublyLinkedList.menu(); + + return 0; +} \ No newline at end of file diff --git a/Doubly Linked List CRUD/LinkedList/Easy/LinkedList.java b/Doubly Linked List CRUD/LinkedList/Easy/LinkedList.java new file mode 100644 index 00000000..d4225fcc --- /dev/null +++ b/Doubly Linked List CRUD/LinkedList/Easy/LinkedList.java @@ -0,0 +1,108 @@ +import java.util.Scanner; + +class Node { + int data; + Node next; + Node prev; + + Node(int data) { + this.data = data; + } +} + +class DoubleLinkedList { + Node head; + int size = 0; + + // Insertion operation (Create) + void insert(int data) { + if (head == null) { + // If the list is empty, create a new node and set it as the head + head = new Node(data); + } else { + // Otherwise, create a new node, update links, and set it as the new head + Node temp = new Node(data); + temp.next = head; + head.prev = temp; + head = temp; + } + size++; + } + + // Deletion operation (Delete) + void delete() { + if (head == null) { + // If the list is empty, do nothing + System.out.println("List is empty. Cannot delete."); + } else { + // Move the head to the next node, update links, and decrease the size + head = head.next; + if (head != null) { + head.prev = null; + } + size--; + System.out.printl("Node deleted successfully."); + } + } + + // Display operation (Read) + void print() { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } + System.out.println(); + } + + // Size operation (Read) + void displaySize() { + System.out.println("Size of the list: " + this.size); + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + DoubleLinkedList doublyLinkedList = new DoubleLinkedList(); + + while (true) { + System.out.println("\nChoose operation:"); + System.out.println("1. Insert"); + System.out.println("2. Delete"); + System.out.println("3. Display"); + System.out.println("4. Display Size"); + System.out.println("5. Exit"); + + int choice = scanner.nextInt(); + + switch (choice) { + case 1: + System.out.println("Enter data to insert:"); + int dataToInsert = scanner.nextInt(); + doublyLinkedList.insert(dataToInsert); + System.out.println("Node inserted successfully."); + break; + + case 2: + doublyLinkedList.delete(); + break; + + case 3: + System.out.println("Elements in the list:"); + doublyLinkedList.print(); + break; + + case 4: + doublyLinkedList.displaySize(); + break; + + case 5: + System.out.println("Exiting the program."); + scanner.close(); + System.exit(0); + + default: + System.out.println("Invalid choice. Please try again."); + } + } + } +} diff --git a/Linked List/Medium/Finding loop in linkedlist/FindingLoop.cpp b/Linked List/Medium/Finding loop in linkedlist/FindingLoop.cpp new file mode 100644 index 00000000..4716278b --- /dev/null +++ b/Linked List/Medium/Finding loop in linkedlist/FindingLoop.cpp @@ -0,0 +1,133 @@ +#include +using namespace std; + +/* Node class definition */ +class VSDnode { +public: + int data; + VSDnode* next; + + VSDnode(int val) { + data = val; + next = NULL; + } +}; + +/* Function to add a node at the head of the linked list */ +void add_head(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + n->next = head; + head = n; +} + +/* Function to add a node at the tail of the linked list */ +void add_tail(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + if (head == NULL) { + head = n; + return; + } + VSDnode* temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = n; +} + +/* Function to create a cycle in the linked list at a specified position */ +void create_cycle_pos(VSDnode* &head, int pos) { + VSDnode* temp = head; + int len = 1; + VSDnode* ptr; + while (temp->next != NULL) { + if (len == pos) { + ptr = temp; + } + temp = temp->next; + len++; + } + temp->next = ptr; +} + +/* Function to detect the presence of a cycle in the linked list using Floyd's Tortoise and Hare algorithm */ +bool detect_cycle(VSDnode* &head) { + VSDnode* slow = head; + VSDnode* fast = head; + while (fast != NULL && fast->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (fast == slow) { + return true; /* Cycle present in the linked list */ + } + } + return false; /* No cycle present in the linked list */ +} + +/* Function to remove the cycle in the linked list */ +void remove_cycle(VSDnode* &head) { + VSDnode* slow = head; + VSDnode* fast = head; + + do { + slow = slow->next; + fast = fast->next->next; + } while (slow != fast); + + fast = head; + while (slow->next != fast->next) { + slow = slow->next; + fast = fast->next; + } + slow->next = NULL; +} + +/* Function to display the linked list */ +void display(VSDnode* head) { + VSDnode* temp = head; + while (temp != NULL) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; +} + +int main() { + VSDnode* head = NULL; + int n; + + cout << "Enter the number of elements in the linked list: "; + cin >> n; + + cout << "Enter the elements of the linked list:" << endl; + for (int i = 0; i < n; i++) { + int element; + cin >> element; + add_tail(head, element); + } + + cout << "Do you want to create a cycle in the linked list? (1 for Yes, 0 for No): "; + int createCycle; + cin >> createCycle; + + if (createCycle) { + cout << "Enter the position to create a cycle: "; + int pos; + cin >> pos; + create_cycle_pos(head, pos); + } + + cout << "Linked List: "; + display(head); + + /* Detecting and displaying whether a cycle is present */ + if (detect_cycle(head)) { + cout << "Cycle present in the linked list" << endl; + remove_cycle(head); + cout << "Linked List after removing the cycle: "; + display(head); + } else { + cout << "No cycle present in the linked list" << endl; + } + + return 0; +} diff --git a/Linked List/Medium/Finding loop in linkedlist/Findingloop.py b/Linked List/Medium/Finding loop in linkedlist/Findingloop.py new file mode 100644 index 00000000..a99e49e3 --- /dev/null +++ b/Linked List/Medium/Finding loop in linkedlist/Findingloop.py @@ -0,0 +1,129 @@ +class Node: + def __init__(self, val): + self.data = val + self.next = None + +class SLL: + def __init__(self): + self.head = None + + def insert_begin(self, val): + # Insert a new node at the beginning of the linked list + new_node = Node(val) + new_node.next = self.head + self.head = new_node + + def insert_end(self, val): + # Insert a new node at the end of the linked list + new_node = Node(val) + if self.head is None: + self.head = new_node + else: + temp = self.head + while temp.next: + temp = temp.next + temp.next = new_node + + def insert_pos(self, val, pos): + # Insert a new node at a specified position in the linked list + if pos < 1: + print("Invalid position for insertion.") + return + + count = 0 + temp = self.head + while temp: + count += 1 + if count == pos - 1: + break + temp = temp.next + + if temp is None: + print("Invalid position for insertion.") + return + + new_node = Node(val) + new_node.next = temp.next + temp.next = new_node + + def create_loop(self, position, by_value=True): + # Create a loop in the linked list either by value or position + count = 0 + temp = self.head + while temp.next: + count += 1 + if (by_value and count == position) or (not by_value and count == position - 1): + loop_node = temp.next + break + temp = temp.next + + temp.next = loop_node + + def detect_loop(self): + # Detect a loop in the linked list using Floyd's Tortoise and Hare algorithm + slow = self.head + fast = self.head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + print("Loop detected in the linked list.") + return slow # Return the node where the loop starts + + print("No loop found in the linked list.") + return None + + def remove_loop(self): + # Remove the loop in the linked list using Floyd's Tortoise and Hare algorithm + loop_start = self.detect_loop() + if loop_start: + slow = self.head + fast = loop_start + + while slow.next != fast.next: + slow = slow.next + fast = fast.next + + fast.next = None + + def display(self): + # Display the elements of the linked list + temp = self.head + while temp: + print(temp.data, end=" -> ") + temp = temp.next + print("None") + + +# Test drive code with user input: +sll = SLL() + +print("------------INSERTION OPERATIONS-------------") +n = int(input("Enter the number of elements to insert at the beginning: ")) +for _ in range(n): + val = int(input("Enter the value to insert at the beginning: ")) + sll.insert_begin(val) +sll.display() + +n = int(input("Enter the number of elements to insert at the end: ")) +for _ in range(n): + val = int(input("Enter the value to insert at the end: ")) + sll.insert_end(val) +sll.display() + +val = int(input("Enter the value to insert: ")) +pos = int(input("Enter the position to insert at: ")) +sll.insert_pos(val, pos) +sll.display() + +print("------------LOOP CREATION-------------") +pos = int(input("Enter the position for loop creation: ")) +sll.create_loop(pos) +sll.display() + +print("------------LOOP DETECTION-------------") +sll.detect_loop() + +print("------------LOOP REMOVAL-------------") +sll.remove_loop() +sll.display() \ No newline at end of file diff --git a/Linked List/Medium/Finding loop in linkedlist/VSDFindingLoopInLinkedList.java b/Linked List/Medium/Finding loop in linkedlist/VSDFindingLoopInLinkedList.java new file mode 100644 index 00000000..89e37177 --- /dev/null +++ b/Linked List/Medium/Finding loop in linkedlist/VSDFindingLoopInLinkedList.java @@ -0,0 +1,83 @@ +import java.util.*; + +public class VSDFindingLoopInLinkedList { + // Class to hold the structure of a node + private static class VSDNode { + int data; // data of node + VSDNode next; // pointer to next element in the list + + VSDNode(int data) { + this.data = data; + this.next = null; + } + } + + static VSDNode head = null; + + // Function to insert elements into the linked list + public static void VSDinsert(int element) { + VSDNode temp = new VSDNode(element); // creating a new node with the given data + if (head == null) + head = temp; // inserting the first element as head + else { + VSDNode x = head; + while (x.next != null) { + x = x.next; + } + x.next = temp; // inserting node at the end of the linked list + } + } + + // Function to check whether a loop exists in the linked list + public static boolean VSDfindLoop() { + VSDNode slow = head; + VSDNode fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; // Move one step at a time + fast = fast.next.next; // Move two steps at a time + + if (slow == fast) { + return true; // If there is a loop, slow and fast will meet at some point + } + } + return false; + } + + public static void main(String args[]) { + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the number of elements in the linked list:"); + int n = scanner.nextInt(); + + System.out.println("Enter the elements of the linked list:"); + + for (int i = 0; i < n; i++) { + int element = scanner.nextInt(); + VSDinsert(element); + } + + // Asking the user whether to create a loop + System.out.println("Do you want to create a loop in the linked list? (yes/no)"); + String createLoop = scanner.next(); + + if (createLoop.equalsIgnoreCase("yes")) { + // Creating a loop by making the last node point to the head + VSDNode lastNode = head; + while (lastNode.next != null) { + lastNode = lastNode.next; + } + lastNode.next = head; + } + + boolean hasLoop = VSDfindLoop(); + + if (hasLoop) + System.out.println("The linked list contains a loop"); + else + System.out.println("The linked list does not contain a loop"); + + scanner.close(); + } +} + diff --git a/LinkedList/Easy/LinkedListPalindrome/Main.java b/LinkedList/Easy/LinkedListPalindrome/Main.java new file mode 100644 index 00000000..8d599b74 --- /dev/null +++ b/LinkedList/Easy/LinkedListPalindrome/Main.java @@ -0,0 +1,77 @@ +import java.util.Scanner; +import java.util.Stack; + +class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + } +} + +public class Main { + + // Function to create a linked list from an array of values + static Node createList(int[] values) { + Node head = null, temp = null; + for (int value : values) { + if (temp == null) { + temp = new Node(value); + head = temp; + } else { + temp.next = new Node(value); + temp = temp.next; + } + } + return head; + } + + // Function to check if a linked list is a palindrome + static boolean checkPalindrome(Node head) { + Node temp = head; + Stack stack = new Stack<>(); + + // Push elements of the first half onto the stack + while (head != null) { + stack.push(head.data); + head = head.next; + } + + // Compare the second half with the elements popped from the stack + while (temp != null) { + if (temp.data != stack.pop()) return false; + temp = temp.next; + } + + return true; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Prompt the user to enter values for the linked list + System.out.print("Enter elements of the linked list separated by spaces: "); + String userInput = scanner.nextLine(); + String[] valuesString = userInput.split(" "); + + // Convert the input values to integers + int[] values = new int[valuesString.length]; + for (int i = 0; i < valuesString.length; i++) { + values[i] = Integer.parseInt(valuesString[i]); + } + + // Create the linked list + Node head = createList(values); + + // Check if the linked list is a palindrome + boolean result = checkPalindrome(head); + + // Print the result + if (result) { + System.out.println("The linked list is a palindrome."); + } else { + System.out.println("The linked list is not a palindrome."); + } + } +} diff --git a/LinkedList/Easy/LinkedListPalindrome/palindrome.cpp b/LinkedList/Easy/LinkedListPalindrome/palindrome.cpp new file mode 100644 index 00000000..d3cf0285 --- /dev/null +++ b/LinkedList/Easy/LinkedListPalindrome/palindrome.cpp @@ -0,0 +1,100 @@ +#include +using namespace std; + +/* Node class for the linked list */ +class VSDnode { +public: + int data; + VSDnode* next; + + /* Constructor to initialize node with given value */ + VSDnode(int val) { + data = val; + next = NULL; + } +}; + +/* Function to add a new node at the head of the linked list */ +void add_head(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + n->next = head; + head = n; +} + +/* Function to add a new node at the tail of the linked list */ +void add_tail(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + if (head == NULL) { + head = n; + return; + } + VSDnode* temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = n; +} + +/* Function to display the linked list */ +void display(VSDnode* head) { + VSDnode* temp = head; + while (temp != NULL) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; +} + +/* Function to reverse the linked list */ +VSDnode* reverse(VSDnode* head) { + VSDnode* prev = NULL; + VSDnode* curr = head; + + while (curr) { + VSDnode* next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + return prev; +} + +/* Function to check if the linked list is a palindrome */ +void is_palindrome(VSDnode* head) { + VSDnode* new_head = reverse(head); + VSDnode* temp1 = head; + VSDnode* temp2 = new_head; + + while (temp1) { + if (temp1->data != temp2->data) { + cout << "The linked list is not a palindrome" << endl; + return; + } + temp1 = temp1->next; + temp2 = temp2->next; + } + cout << "The linked list is a palindrome" << endl; +} + +int main() { + cout << "Enter the number of elements in the linked list: "; + int n; + cin >> n; + + VSDnode* head = NULL; + + cout << "Enter the elements of the linked list:" << endl; + for (int i = 0; i < n; ++i) { + int val; + cin >> val; + add_tail(head, val); + } + + cout << "Linked List:" << endl; + display(head); + + /* Check if the linked list is a palindrome */ + is_palindrome(head); + + return 0; +} diff --git a/LinkedList/Easy/LinkedListPalindrome/palindrome.py b/LinkedList/Easy/LinkedListPalindrome/palindrome.py new file mode 100644 index 00000000..f215c7a0 --- /dev/null +++ b/LinkedList/Easy/LinkedListPalindrome/palindrome.py @@ -0,0 +1,50 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + +def create_list(llist): + head = None + temp = None + for i in llist: + if not temp: + temp = Node(i) + head = temp + else: + temp.next = Node(i) + temp = temp.next + return head + +def check_palindrome(head): + temp = head + stack = [] + + # Push elements of the first half onto the stack + while head: + stack.append(head.data) + head = head.next + + # Compare the second half with the elements popped from the stack + while temp: + if temp.data != stack.pop(): + return False + temp = temp.next + + return True + +if __name__ == "__main__": + # Take user input for the linked list + user_input = input("Enter elements of the linked list separated by spaces: ") + llist = list(map(int, user_input.split())) + + # Create the linked list + head = create_list(llist) + + # Check if the linked list is a palindrome + result = check_palindrome(head) + + # Print the result + if result: + print("The linked list is a palindrome.") + else: + print("The linked list is not a palindrome.") diff --git a/Sorting/Hard/Array Heap Sort/Main.java b/Sorting/Hard/Array Heap Sort/Main.java new file mode 100644 index 00000000..88db82ff --- /dev/null +++ b/Sorting/Hard/Array Heap Sort/Main.java @@ -0,0 +1,118 @@ +import java.util.Scanner; + +public class Main { + + // Function to swap elements at indices i and j in the array + static void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + // Function to maintain max heap properties + static void VSDmaxheapify(int[] arr, int n, int i) { + int large = i; + int leftChild = 2 * i + 1; + int rightChild = 2 * i + 2; + + if (leftChild < n && arr[i] < arr[leftChild]) { + large = leftChild; + } + + if (rightChild < n && arr[large] < arr[rightChild]) { + large = rightChild; + } + + if (large != i) { + swap(arr, i, large); + VSDmaxheapify(arr, n, large); + } + } + + // Function to maintain min heap properties + static void VSDminheapify(int[] arr, int n, int i) { + int small = i; + int leftChild = 2 * i + 1; + int rightChild = 2 * i + 2; + + if (leftChild < n && arr[i] > arr[leftChild]) { + small = leftChild; + } + + if (rightChild < n && arr[small] > arr[rightChild]) { + small = rightChild; + } + + if (small != i) { + swap(arr, i, small); + VSDminheapify(arr, n, small); + } + } + + // Function to perform max heap sort + static void VSDMaxheapsort(int[] arr) { + int n = arr.length; + + // Build max heap + for (int i = n / 2 - 1; i >= 0; i--) { + VSDmaxheapify(arr, n, i); + } + + // Extract elements one by one + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDmaxheapify(arr, i, 0); + } + } + + // Function to perform min heap sort + static void VSDMinheapsort(int[] arr) { + int n = arr.length; + + // Build min heap + for (int i = n / 2 - 1; i >= 0; i--) { + VSDminheapify(arr, n, i); + } + + // Extract elements one by one + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDminheapify(arr, i, 0); + } + } + + // Function to print array + static void printArray(int[] arr) { + for (int a : arr) { + System.out.print(a + " "); + } + System.out.println(); + } + + public static void main(String args[]) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the number of elements: "); + int n = scanner.nextInt(); + + int[] arr = new int[n]; + + System.out.println("Enter the elements:"); + for (int i = 0; i < n; i++) { + arr[i] = scanner.nextInt(); + } + + System.out.println("Original array:"); + printArray(arr); + + // Sorting in ascending order using max heap sort + VSDMaxheapsort(arr); + System.out.println("Sorted array in ascending order:"); + printArray(arr); + + // Sorting in descending order using min heap sort + VSDMinheapsort(arr); + System.out.println("Sorted array in descending order:"); + printArray(arr); + } +} \ No newline at end of file diff --git a/Sorting/Hard/Array Heap Sort/sort.cpp b/Sorting/Hard/Array Heap Sort/sort.cpp new file mode 100644 index 00000000..52553416 --- /dev/null +++ b/Sorting/Hard/Array Heap Sort/sort.cpp @@ -0,0 +1,105 @@ +#include +using namespace std; + +/* Function to swap elements at indices i and j in the array */ +void swap(int arr[], int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + +/* Function to print the elements of an array */ +void printarray(int arr[], int n) { + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + cout << endl; +} + +/* Function to maintain max heap properties*/ +void VSDmaxheapify(int arr[], int n, int i) { + int large = i; + int leftchild = (2 * i) + 1; + int rightchild = (2 * i) + 2; + + if (leftchild < n && arr[i] < arr[leftchild]) + large = leftchild; + if (rightchild < n && arr[large] < arr[rightchild]) + large = rightchild; + if (large != i) { + swap(arr, i, large); + VSDmaxheapify(arr, n, large); + } +} + +/* Function to maintain min heap properties */ +void VSDminheapify(int arr[], int n, int i) { + int small = i; + int leftchild = (2 * i) + 1; + int rightchild = (2 * i) + 2; + + if (leftchild < n && arr[i] > arr[leftchild]) { + small = leftchild; + } + if (rightchild < n && arr[small] > arr[rightchild]) { + small = rightchild; + } + if (small != i) { + swap(arr, small, i); + VSDminheapify(arr, n, small); + } +} + +/* Function to perform max heap sort */ +void VSDMaxheapsort(int arr[], int n) { + /* Build max heap */ + for (int i = (n / 2) - 1; i >= 0; i--) { + VSDmaxheapify(arr, n, i); + } + + /* Extract elements one by one */ + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDmaxheapify(arr, i, 0); + } +} + +/* Function to perform min heap sort */ +void VSDMinheapsort(int arr[], int n) { + /* Build min heap */ + for (int i = (n / 2) - 1; i >= 0; i--) { + VSDminheapify(arr, n, i); + } + + /* Extract elements one by one */ + for (int i = n - 1; i > 0; i--) { + swap(arr, i, 0); + VSDminheapify(arr, i, 0); + } +} + +int main() { + /* Taking user input for the number of elements */ + cout << "Enter the number of elements: "; + int n; + cin >> n; + + /* Taking user input for the array */ + int arr[n]; + cout << "Enter the elements: "; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + /* Sorting in ascending order using max heap sort */ + VSDMaxheapsort(arr, n); + cout << "Sorted array in ascending order: "; + printarray(arr, n); + + /* Sorting in descending order using min heap sort */ + VSDMinheapsort(arr, n); + cout << "Sorted array in descending order: "; + printarray(arr, n); + + return 0; +} diff --git a/Sorting/Hard/Array Heap Sort/sort.py b/Sorting/Hard/Array Heap Sort/sort.py new file mode 100644 index 00000000..7c36f2e6 --- /dev/null +++ b/Sorting/Hard/Array Heap Sort/sort.py @@ -0,0 +1,123 @@ +# Function to maintain max heap properties +# Function to maintain max heap properties +def VSDmaxHeapify(arr, size, i): + # Declare current element index as largest element + large = i + + # Find index of left child + leftchild = (2 * i) + 1 + + # Find index of right child + rightchild = (2 * i) + 2 + + # Check largest element between left child and current element + if leftchild < size and arr[i] < arr[leftchild]: + large = leftchild + + # Check largest element between right child and large element + if rightchild < size and arr[large] < arr[rightchild]: + large = rightchild + + # If large element is not the current element + # Swap current element with large element + # Heapify the current array + if large != i: + arr[large], arr[i] = arr[i], arr[large] + VSDmaxHeapify(arr, size, large) + + +# Function to maintain min heap properties +def VSDminHeapify(arr, size, i): + # Declare current element index as smallest + small = i + + # Find index of left child + leftchild = (2 * i) + 1 + + # Find index of right child + rightchild = (2 * i) + 2 + + # Check smallest element between left child and current element + if leftchild < size and arr[i] > arr[leftchild]: + small = leftchild + + # Check smallest element between right child and smallest element + if rightchild < size and arr[small] > arr[rightchild]: + small = rightchild + + # If smallest element is not the current element + # Swap smallest element and current element + # Heapify the current array + if small != i: + arr[small], arr[i] = arr[i], arr[small] + VSDminHeapify(arr, size, small) + + +# Function to insert elements into max heap +def insert(array, num): + if len(array) == 0: + array.append(num) + else: + array.append(num) + for i in range(len(array)): + VSDmaxHeapify(array, len(array), i) + + +# Function to sort the given array using max heap in ascending order +def VSDMaxheapsort(array): + size = len(array) + + # Heapify the given array into max heap + for i in range((size // 2) - 1, -1, -1): + VSDmaxHeapify(array, size, i) + + # Find the max element in array + # Swap the max element with last index element + # Decrease the last index by 1 + # Heapify the current array up to the last index + for i in range(size - 1, 0, -1): + array[i], array[0] = array[0], array[i] + VSDmaxHeapify(array, i, 0) + + +# Function to sort the given array using min heap in descending order +def VSDMinheapsort(array): + size = len(array) + + # Heapify the given array into min heap + for i in range((size // 2) - 1, -1, -1): + VSDminHeapify(array, size, i) + + # Find the min element in array + # Swap the min element with last index element + # Decrease the last index by 1 + # Heapify the current array up to the last index + for i in range(size - 1, -1, -1): + array[0], array[i] = array[i], array[0] + VSDminHeapify(array, i, 0) + + +# Function to print array +def printarray(array): + for i in array: + print(i, end=" ") + print() + + +if __name__ == "__main__": + # Taking user input for the array + user_input = input("Enter numbers separated by spaces: ") + arr = list(map(int, user_input.split())) + + print("Original array:") + printarray(arr) + + # Sorting in ascending order using max heap sort + VSDMaxheapsort(arr) + print("Sorted array in ascending order:") + printarray(arr) + + # Sorting in descending order using min heap sort + VSDMinheapsort(arr) + print("Sorted array in descending order:") + printarray(arr) diff --git a/Stack Crud LinkedList/Deque/Easy/Stack.java b/Stack Crud LinkedList/Deque/Easy/Stack.java new file mode 100644 index 00000000..a041bcf0 --- /dev/null +++ b/Stack Crud LinkedList/Deque/Easy/Stack.java @@ -0,0 +1,104 @@ +import java.util.Scanner; + +class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + } +} + +class Stack { + Node top; + + // Push operation: Add a new node with the specified data to the top of the stack. + void push(int data) { + if (top == null) { + // If the stack is empty, create the first node. + top = new Node(data); + } else { + // If the stack is not empty, create a new node and update the top. + Node temp = new Node(data); + temp.next = top; + top = temp; + } + } + + // Pop operation: Remove the top node from the stack. + void pop() { + if (top != null) { + // If the stack is not empty, update the top to the next node. + top = top.next; + } + } + + // Peek operation: Print the data of the top node without removing it. + void peek() { + if (top != null) { + // If the stack is not empty, print the data of the top node. + System.out.println("Peek: " + top.data); + } + } + + // Recursive print method: Print all elements in the stack from top to bottom. + void printRecursive(Node temp) { + if (temp != null) { + printRecursive(temp.next); + System.out.print(temp.data + " "); + } + } + + // Print operation: Print all the elements in the stack from top to bottom. + void print() { + if (top != null) { + System.out.print("Stack elements: "); + // Call the recursive print method to print elements. + printRecursive(top); + System.out.println(); + } + } +} + +public class Main { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Stack stack = new Stack(); + + while (true) { + System.out.println("\nChoose an operation:"); + System.out.println("1. Push"); + System.out.println("2. Pop"); + System.out.println("3. Peek"); + System.out.println("4. Print"); + System.out.println("5. Exit"); + + int choice = scanner.nextInt(); + + switch (choice) { + case 1: + System.out.println("Enter the value to push:"); + int pushValue = scanner.nextInt(); + stack.push(pushValue); + break; + case 2: + stack.pop(); + break; + case 3: + stack.peek(); + break; + case 4: + stack.print(); + break; + case 5: + System.out.println("Exiting the program."); + scanner.close(); + System.exit(0); + break; + default: + System.out.println("Invalid choice. Please try again."); + } + } + } +} + diff --git a/Stack Crud LinkedList/Deque/Easy/stack.cpp b/Stack Crud LinkedList/Deque/Easy/stack.cpp new file mode 100644 index 00000000..08b89e6f --- /dev/null +++ b/Stack Crud LinkedList/Deque/Easy/stack.cpp @@ -0,0 +1,92 @@ +#include +using namespace std; + +class VSDnode { +public: + int data; + VSDnode* next; + + VSDnode(int val) { + data = val; + next = NULL; + } +}; + +/* Function to push a new element onto the stack*/ +void VSDpush(VSDnode* &head, int val) { + VSDnode* n = new VSDnode(val); + n->next = head; + head = n; +} + +/* Function to pop the top element from the stack */ +void VSDpop(VSDnode* &head) { + if (head == NULL) { + cout << "Stack is empty. Cannot pop." << endl; + } else { + head = head->next; + } +} + +/* Function to get the top element of the stack */ +void VSDtop(VSDnode* &head) { + if (head != NULL) { + cout << "The top of the stack is: " << head->data << endl; + } else { + cout << "Stack is empty. Cannot get top." << endl; + } +} + +/* Function to display the elements of the stack */ +void VSDdisplay(VSDnode* head) { + VSDnode* temp = head; + while (temp != NULL) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; +} + +int main() { + VSDnode* head = NULL; + + while (true) { + cout << "\nStack Operations:" << endl; + cout << "1. Push" << endl; + cout << "2. Pop" << endl; + cout << "3. Top" << endl; + cout << "4. Display" << endl; + cout << "5. Quit" << endl; + + int choice; + cout << "Enter your choice (1/2/3/4/5): "; + cin >> choice; + + switch (choice) { + case 1: { + int val; + cout << "Enter the value to push onto the stack: "; + cin >> val; + VSDpush(head, val); + cout << val << " pushed onto the stack." << endl; + break; + } + case 2: + VSDpop(head); + break; + case 3: + VSDtop(head); + break; + case 4: + VSDdisplay(head); + break; + case 5: + cout << "Quitting the program." << endl; + return 0; + default: + cout << "Invalid choice. Please enter 1, 2, 3, 4, or 5." << endl; + } + } + + return 0; +} diff --git a/Stack Crud LinkedList/Deque/Easy/stack.py b/Stack Crud LinkedList/Deque/Easy/stack.py new file mode 100644 index 00000000..df525ca0 --- /dev/null +++ b/Stack Crud LinkedList/Deque/Easy/stack.py @@ -0,0 +1,65 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class StackLL: + def __init__(self): + self.top = None + + def isempty(self): + #Check if the stack is empty.# + return not self.top + + def push(self, data): + #Push a new element onto the stack. + if not self.top: + self.top = Node(data) + else: + temp = Node(data) + temp.next = self.top + self.top = temp + + def pop(self): + #Pop the top element from the stack and return its value. + if self.top: + x = self.top.data + self.top = self.top.next + return x + else: + print("Stack is empty. Cannot pop.") + + def traverse(self): + #Traverse and print the elements in the stack. + head = self.top + while head: + print(head.data, end=" ") + head = head.next + print() +# Create an instance of StackLL +stack = StackLL() +while True: + print("\nSelect stack operation:") + print("1. Push") + print("2. Pop") + print("3. Display") + print("4. Exit") + + choice = input("Enter choice (1/2/3/4): ") + + if choice == '1': + data = input("Enter data to push onto the stack: ") + stack.push(data) + print(f"{data} pushed onto the stack.") + elif choice == '2': + popped_element = stack.pop() + if popped_element is not None: + print(f"Popped element: {popped_element}") + elif choice == '3': + print("Stack elements:") + stack.traverse() + elif choice == '4': + print("Exiting the program.") + break + else: + print("Invalid choice. Please enter a valid option.")