|
| 1 | +# Implementation of Singly Linked List in Python |
| 2 | +# Define a class to represent a node in the linked list |
| 3 | +class Node: |
| 4 | + def __init__(self, data): |
| 5 | + # Each node has two attributes: data and a reference to the next node |
| 6 | + self.data = data |
| 7 | + self.next = None |
| 8 | + |
| 9 | +# Define a class to represent the linked list itself |
| 10 | +class LinkedList: |
| 11 | + def __init__(self): |
| 12 | + # Each linked list has one attribute: the head node (which initially is None) |
| 13 | + self.head = None |
| 14 | + |
| 15 | + # Method to insert a new node at the beginning of the linked list |
| 16 | + def insert_at_beginning(self, data): |
| 17 | + # Create a new node |
| 18 | + new_node = Node(data) |
| 19 | + |
| 20 | + # Set the next node of the new node to be the current head node |
| 21 | + new_node.next = self.head |
| 22 | + |
| 23 | + # Set the head node to be the new node |
| 24 | + self.head = new_node |
| 25 | + |
| 26 | + # Method to insert a new node at the end of the linked list |
| 27 | + def insert_at_end(self, data): |
| 28 | + # Create a new node |
| 29 | + new_node = Node(data) |
| 30 | + |
| 31 | + # If the list is empty, set the head node to be the new node |
| 32 | + if self.head is None: |
| 33 | + self.head = new_node |
| 34 | + return |
| 35 | + |
| 36 | + # Traverse to the last node in the list |
| 37 | + current_node = self.head |
| 38 | + while current_node.next: |
| 39 | + current_node = current_node.next |
| 40 | + |
| 41 | + # Set the next node of the last node to be the new node |
| 42 | + current_node.next = new_node |
| 43 | + |
| 44 | + # Method to delete the first occurrence of a node with the given data |
| 45 | + def delete_node(self, data): |
| 46 | + # If the list is empty, do nothing |
| 47 | + if self.head is None: |
| 48 | + return |
| 49 | + |
| 50 | + # If the node to be deleted is the head node, set the head node to be the next node |
| 51 | + if self.head.data == data: |
| 52 | + self.head = self.head.next |
| 53 | + return |
| 54 | + |
| 55 | + # Traverse the list to find the node to be deleted |
| 56 | + current_node = self.head |
| 57 | + while current_node.next: |
| 58 | + if current_node.next.data == data: |
| 59 | + current_node.next = current_node.next.next |
| 60 | + return |
| 61 | + current_node = current_node.next |
| 62 | + |
| 63 | + # Method to print the linked list |
| 64 | + def print_list(self): |
| 65 | + # Traverse the list and print each node's data |
| 66 | + current_node = self.head |
| 67 | + while current_node: |
| 68 | + print(current_node.data, end=" -> ") |
| 69 | + current_node = current_node.next |
| 70 | + print("None") |
0 commit comments