Write a program that implements a singly linked list with insert and delete operations.
- User
Write a program that implements a singly linked list with insert and delete operations.
Assistant
Write a program that implements a singly linked list with insert and delete operations.
The user wants a program that implements a singly linked list. The specific operations required are:
I need to choose a programming language. Python, C++, and Java are the most common choices for data structure implementations.
I will provide the solution in Python because it's highly readable and widely understood, but I'll also provide a C++ version because linked lists are a classic topic where pointer logic is key. This adds value.
Plan:
Define the Node class:
data.next (pointer/reference to the next node).Define the LinkedList class:
head (pointer to the start of the list).Implement Insert:
insert_at_end and insert_at_beginning to be thorough.Implement Delete:
Implement Display/Traversal:
Construct the Code (Python Example):
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data): # Let's do append for standard list behavior
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def delete(self, key):
curr = self.head
prev = None
# Case 1: List is empty
if not curr:
return
# Case 2: Head holds the key
if curr.data == key:
self.head = curr.next
return
# Case 3: Search for the key
while curr and curr.data != key:
prev = curr
curr = curr.next
# If key was not present
if not curr:
return
# Unlink
prev.next = curr.next
Construct the Code (C++ Example):
new operator for allocation.Review and Refine:
The prompt is simple: "Write a program". I should provide a complete, runnable example with a main/driver code section to demonstrate the functionality.
I will stick to Python as the primary answer for readability, but perhaps mention C++ logic or offer it if the user usually codes in system languages. Actually, providing both might be overkill unless asked, but providing Python is the safest bet for general users. I will provide Python, as it's the most accessible pseudo-code like language, but strict enough to run.
Let's refine the Python code to be clean and include comments.
I will add a print_list method so the user can see the result.
I will add a driver code block at the bottom.
Drafting the Python response:
Node: Holds data and next.LinkedList: Holds head.append(data): Adds to the end.delete_node(key): Removes the first occurrence of key.display(): Prints the list.Drafting the C++ response (optional but good):
Final Decision on Format:
This covers all bases.
Self-Correction during drafting:
delete, make sure to handle the case where the head is None (empty list).delete, make sure to handle the case where the head is the one to be deleted.delete, if the key isn't found, do nothing (don't crash).Let's write the Python code mentally:
def delete_node(self, key):
temp = self.head
# Case 1: Head is the key
if temp and temp.data == key:
self.head = temp.next
temp = None # Help garbage collection (not strictly necessary in Python but good practice conceptually)
return
# Search
prev = None
while temp and temp.data != key:
prev = temp
temp = temp.next
# If key not found
if temp is None:
return
# Unlink
prev.next = temp.next
temp = None
This logic is sound.
Let's write the C++ code mentally:
void deleteNode(int key) {
if (head == nullptr) return;
Node* temp = head;
Node* prev = nullptr;
if (temp != nullptr && temp->data == key) {
head = temp->next;
delete temp;
return;
}
while (temp != nullptr && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == nullptr) return;
prev->next = temp->next;
delete temp;
}
This logic is also sound.
I will output the Python version primarily, as it's most universally readable, and include the C++ version as an alternative since linked lists are pointer-heavy concepts often associated with C/C++.
Here are complete implementations in both Python and C++. These examples include the Node structure, the LinkedList class, methods for insertion (at the end) and deletion (by value), and a helper function to print the list.
Python handles memory management automatically, which makes the logic very readable.
class Node:
def __init__(self, data):
self.data = data # The value stored in the node
self.next = None # Reference to the next node (initially None)
class LinkedList:
def __init__(self):
self.head = None # The list starts empty
# Operation 1: Insert a new node at the end of the list
def insert(self, data):
new_node = Node(data)
# If the list is empty, make the new node the head
if self.head is None:
self.head = new_node
return
# Otherwise, traverse to the end of the list
last_node = self.head
while last_node.next:
last_node = last_node.next
# Point the last node's next to the new node
last_node.next = new_node
# Operation 2: Delete the first occurrence of a node with specific data
def delete(self, key):
current_node = self.head
# Case 1: The list is empty
if current_node is None:
print("List is empty.")
return
# Case 2: The head node holds the key to be deleted
if current_node.data == key:
self.head = current_node.next
current_node = None # Help garbage collection
return
# Case 3: Search for the key in the rest of the list
prev = None
while current_node is not None and current_node.data != key:
prev = current_node
current_node = current_node.next
# If the key was not found
if current_node is None:
print(f"Value {key} not found in list.")
return
# Unlink the node from the linked list
prev.next = current_node.next
current_node = None
# Helper: Print the list contents
def display(self):
nodes = []
current = self.head
while current:
nodes.append(str(current.data))
current = current.next
print(" -> ".join(nodes))
# --- Driver Code (Testing the operations) ---
if __name__ == "__main__":
ll = LinkedList()
print("Inserting 10, 20, 30...")
ll.insert(10)
ll.insert(20)
ll.insert(30)
ll.display() # Output: 10 -> 20 -> 30
print("\nDeleting 20...")
ll.delete(20)
ll.display() # Output: 10 -> 30
print("\nDeleting 10 (Head node)...")
ll.delete(10)
ll.display() # Output: 30
C++ requires manual memory management (using new and delete), which is a critical part of implementing linked lists in system programming.
#include <iostream>
// Definition of the Node structure
struct Node {
int data;
Node* next;
// Constructor for convenience
Node(int val) {
data = val;
next = nullptr;
}
};
class LinkedList {
private:
Node* head;
public:
// Constructor
LinkedList() {
head = nullptr;
}
// Operation 1: Insert a new node at the end
void insert(int data) {
Node* newNode = new Node(data);
// If list is empty, make new node the head
if (head == nullptr) {
head = newNode;
return;
}
// Traverse to the end
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
// Link the last node to the new node
temp->next = newNode;
}
// Operation 2: Delete a node by value
void deleteNode(int key) {
if (head == nullptr) {
std::cout << "List is empty." << std::endl;
return;
}
// Case 1: Head node holds the key
if (head->data == key) {
Node* temp = head;
head = head->next;
delete temp; // Free memory
return;
}
// Case 2: Search for the key
Node* temp = head;
Node* prev = nullptr;
while (temp != nullptr && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If key was not found
if (temp == nullptr) {
std::cout << "Value " << key << " not found." << std::endl;
return;
}
// Unlink the node
prev->next = temp->next;
delete temp; // Free memory
}
// Helper: Display the list
void display() {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " -> ";
temp = temp->next;
}
std::cout << "NULL" << std::endl;
}
// Destructor to clean up memory when program ends
~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* nextNode = current->next;
delete current;
current = nextNode;
}
}
};
int main() {
LinkedList ll;
std::cout << "Inserting 10, 20, 30..." << std::endl;
ll.insert(10);
ll.insert(20);
ll.insert(30);
ll.display(); // Output: 10 -> 20 -> 30 -> NULL
std::cout << "\nDeleting 20..." << std::endl;
ll.deleteNode(20);
ll.display(); // Output: 10 -> 30 -> NULL
std::cout << "\nDeleting 10..." << std::endl;
ll.deleteNode(10);
ll.display(); // Output: 30 -> NULL
return 0;
}
Insert:
head is null), point head to the new node.temp) and loop through the list until temp.next is null (the end of the list).temp.next to the new node.Delete:
head is null, do nothing.head, move the head pointer to the next node and delete the old head.current and prev. Move them forward until current finds the value or reaches the end.prev.next to current.next. This bypasses the current node, removing it from the chain.delete the node to free memory.