Skip to content

Commit 4a4d71f

Browse files
Delete Head / Tail / Nth Node
1 parent ba0309e commit 4a4d71f

1 file changed

Lines changed: 120 additions & 0 deletions

File tree

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
"""
2+
Delete a Node at a Given Position in a Singly Linked List
3+
4+
Problem:
5+
Given the head of a singly linked list and a position `x` (1-based indexing),
6+
delete the node present at that position and return the updated head.
7+
8+
Example:
9+
Input:
10+
10 -> 20 -> 30 -> 40
11+
x = 3
12+
13+
Output:
14+
10 -> 20 -> 40
15+
16+
Approach:
17+
1. Handle the empty linked list.
18+
2. If x == 1, delete the head node by returning head.next.
19+
3. Traverse the linked list until reaching the x-th node.
20+
4. Keep track of:
21+
- `temp` : current node
22+
- `prev` : node before the current node
23+
5. Change the previous node's next pointer to skip the node being deleted.
24+
25+
Visualization:
26+
27+
Before deletion (x = 3)
28+
29+
head
30+
31+
32+
10 ───► 20 ───► 30 ───► 40 ───► None
33+
▲ ▲
34+
prev temp
35+
36+
After:
37+
prev.next = temp.next
38+
39+
head
40+
41+
42+
10 ───► 20 ─────────► 40 ───► None
43+
(30 is disconnected)
44+
45+
How the loop works:
46+
47+
Initial:
48+
index = 1
49+
temp = 10
50+
prev = None
51+
52+
Iteration 1:
53+
-----------
54+
prev = 10
55+
temp = 20
56+
index = 2
57+
58+
Iteration 2:
59+
-----------
60+
prev = 20
61+
temp = 30
62+
index = 3
63+
64+
Loop stops because index == x.
65+
66+
Deletion:
67+
---------
68+
prev.next = temp.next
69+
70+
20.next = 40
71+
72+
Result:
73+
10 -> 20 -> 40
74+
75+
Time Complexity:
76+
----------------
77+
O(n)
78+
- In the worst case, we traverse the linked list once.
79+
80+
Space Complexity:
81+
-----------------
82+
O(1)
83+
- Only a few pointer variables are used.
84+
"""
85+
86+
87+
class Node:
88+
def __init__(self, data):
89+
self.data = data
90+
self.next = None
91+
92+
93+
class Solution:
94+
def deleteNode(self, head, x):
95+
# Empty linked list
96+
if head is None:
97+
return None
98+
99+
# Delete the first node
100+
if x == 1:
101+
return head.next
102+
103+
index = 1
104+
prev = None
105+
temp = head
106+
107+
# Traverse until the x-th node
108+
while temp and index < x:
109+
prev = temp
110+
temp = temp.next
111+
index += 1
112+
113+
# If x is greater than the number of nodes
114+
if temp is None:
115+
return head
116+
117+
# Delete the node by skipping it
118+
prev.next = temp.next
119+
120+
return head

0 commit comments

Comments
 (0)