gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Write code c++ for delete node
- User
Write code c++ for delete node
- Assistant
Here is an example of C++ code to delete a node from a singly linked list:
#include <iostream> // Node structure for single linked list struct Node { int data; Node* next; }; // Function to delete a node from the linked list void deleteNode(Node** head, int key) { // If the list is empty if (*head == nullptr) { std::cout << "Linked list is empty. Cannot delete node." << std::endl; return; } // If the key is found in the head node if ((*head)->data == key) { Node* temp = *head; *head = (*head)->next; delete temp; std::cout << "Node with key " << key << " deleted." << std::endl; return; } // Traverse the list to find the node before the key node Node* prev = nullptr; Node* current = *head; while (current != nullptr && current->data != key) { prev = current; current = current->next; } // If the key node is found if (current != nullptr) { prev->next = current->next; delete current; std::cout << "Node with key " << key << " deleted." << std::endl; } else { std::cout << "Node with key " << key << " not found." << std::endl; } } // Function to print the linked list void printList(Node* head) { Node* current = head; while(current != nullptr) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; } int main() { // Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5 Node* head = new Node(); Node* second = new Node(); Node* third = new Node(); Node* fourth = new Node(); Node* fifth = new Node(); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = fourth; fourth->data = 4; fourth->next = fifth; fifth->data = 5; fifth->next = nullptr; std::cout << "Before deletion: "; printList(head); // Delete node with key 3 deleteNode(&head, 3); std::cout << "After deletion: "; printList(head); return 0; }This code defines a
Nodestruct for representing a single linked list node. ThedeleteNodefunction takes a pointer to the head node and the key value to delete, and it deletes the node with the given key from the linked list. TheprintListfunction is used to print the linked list. Finally, in the main function, a sample linked list is created, and thedeleteNodefunction is called to delete a node with a specific key from the list.