Add solution for LL: remove n'th node from end of LL

This commit is contained in:
pro100ton 2025-02-16 20:17:28 +03:00
parent ee33a389a2
commit 5ad7e901cd
3 changed files with 120 additions and 0 deletions

View file

@ -0,0 +1,37 @@
# Remove Node From End of Linked List
You are given the beginning of a linked list head, and an integer n.
Remove the nth node from the end of the list and return the beginning of the list.
Example 1:
Input: head = [1,2,3,4], n = 2
Output: [1,2,4]
Example 2:
Input: head = [5], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 2
Output: [2]
Constraints:
The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
# Edge cases
## size of LL == 1
return None
## n = 1
return head.next
# Solution
- Save head and return it after algo

View file

@ -0,0 +1,43 @@
from typing import List, Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
if not head:
return None
if head.next is None:
return None
perm_head = head
nodes = []
while head:
nodes.append(head)
head = head.next
if n == 1:
nodes[-2].next = None
return perm_head
if n == len(nodes):
return perm_head.next
counter = 1
for i in range(len(nodes) - 1, 0, -1):
if counter == n:
nodes[i - 1].next = nodes[i + 1]
counter += 1
return perm_head
if __name__ == "__main__":
s = Solution()
e3 = ListNode(3, None)
e2 = ListNode(2, e3)
e1 = ListNode(1, e2)
e0 = ListNode(0, e1)
fe = s.removeNthFromEnd(e0, 1)
while fe:
print(f"{fe.val}")
fe = fe.next

View file

@ -0,0 +1,40 @@
from typing import List, Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
N = 0
cur = head
while cur:
N += 1
cur = cur.next
removeIndex = N - n
if removeIndex == 0:
return head.next
cur = head
for i in range(N - 1):
if (i + 1) == removeIndex:
cur.next = cur.next.next
break
cur = cur.next
return head
if __name__ == "__main__":
s = Solution()
e3 = ListNode(3, None)
e2 = ListNode(2, e3)
e1 = ListNode(1, e2)
e0 = ListNode(0, e1)
fe = s.removeNthFromEnd(e0, 1)
while fe:
print(f"{fe.val}")
fe = fe.next