File tree 1 file changed +29
-9
lines changed
data_structures/linked_list
1 file changed +29
-9
lines changed Original file line number Diff line number Diff line change 1
1
class Node :
2
2
def __init__ (self , val ):
3
3
self .val = val
4
- self .next = None
4
+ self .next = None # Specify that next can be a Node or None
5
5
6
6
7
- def remove (head , n ):
7
+ def remove (head : Node , n : int ) -> Node :
8
+ if head is None :
9
+ return None # If the head is None, return None
10
+
11
+ # Create a dummy node that points to the head
8
12
extra = Node (0 )
9
13
extra .next = head
10
- fast = extra
11
- slow = extra
14
+ fast = extra # Make sure fast can be None
15
+ slow = extra # Make sure slow can be None
16
+
17
+ # Move fast ahead by n nodes
12
18
for _ in range (n ):
13
- fast = fast .next
19
+ if fast is not None :
20
+ fast = fast .next
14
21
15
- while fast .next :
22
+ # Move until fast reaches the end
23
+ while fast is not None and fast .next is not None :
16
24
fast = fast .next
17
25
slow = slow .next
18
26
19
- slow .next = slow .next .next
27
+ # Remove the nth node from the end
28
+ if slow is not None and slow .next is not None :
29
+ slow .next = slow .next .next # Link slow to the next of the node to be deleted
20
30
21
- return extra .next
31
+ return extra .next # Return the new head, which may be None if the list is empty
22
32
23
33
24
34
def print_list (head : Node ) -> None :
25
35
curr = head
26
- while curr :
36
+ while curr is not None :
27
37
print (curr .val , end = " " )
28
38
curr = curr .next
39
+ print () # for a new line
29
40
30
41
42
+ # Creating the linked list 1 -> 2 -> 3 -> 4 -> 5
31
43
head = Node (1 )
32
44
head .next = Node (2 )
33
45
head .next .next = Node (3 )
34
46
head .next .next .next = Node (4 )
35
47
head .next .next .next .next = Node (5 )
48
+
49
+ # Print the original list
50
+ print ("Original list:" )
36
51
print_list (head )
52
+
53
+ # Remove the 5th node from the end (the head in this case)
37
54
head = remove (head , 5 )
55
+
56
+ # Print the modified list
57
+ print ("List after removing the 5th node from the end:" )
38
58
print_list (head )
You can’t perform that action at this time.
0 commit comments