-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List.py
More file actions
59 lines (48 loc) · 1.95 KB
/
Linked_List.py
File metadata and controls
59 lines (48 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Linked List
# This is a simple implementation of a linked list in Python. It includes methods to check if the list is empty, add elements to the end of the list, and remove elements from the list. The linked list is implemented using a nested Node class to represent each node in the list.
class LinkedList:
class Node:
def __init__(self, element): # Initialize a new node with the given element and set the next pointer to None
self.element = element
self.next = None
def __init__(self): # Initialize the linked list with a length of 0 and a head pointer set to None
self.length = 0
self.head = None
def is_empty(self): # Check if the linked list is empty by comparing the length to 0
return self.length == 0
def add(self, element): # Add a new element to the end of the linked list
node = self.Node(element)
if self.is_empty():
self.head = node
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = node
self.length += 1
def remove(self, element): # Remove an element from the linked list by traversing the list and updating the next pointers accordingly
previous_node = None
current_node = self.head
while current_node is not None and current_node.element != element:
previous_node = current_node
current_node = current_node.next
if current_node is None:
return
elif previous_node is not None:
previous_node.next = current_node.next
else:
self.head = current_node.next
self.length -= 1
my_list = LinkedList()
print(my_list.is_empty()) # True
my_list.add(1)
my_list.add(2)
print(my_list.is_empty()) # False
print(my_list.length) # 2
my_list.remove(1)
print(my_list.length) # 1
## Output:
# True
# False
# 2
# 1