Skip to content

Commit 01cf981

Browse files
authored
Merge pull request #1 from 149ps/main
o(n) time and o(1) space using two pointers.
2 parents 2399591 + fc9edd4 commit 01cf981

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
You are given the head of a linked list, and an integer k.
3+
4+
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
5+
6+
7+
8+
Example 1:
9+
10+
11+
Input: head = [1,2,3,4,5], k = 2
12+
Output: [1,4,3,2,5]
13+
Example 2:
14+
15+
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
16+
Output: [7,9,6,6,8,7,3,0,9,5]
17+
18+
19+
Constraints:
20+
21+
The number of nodes in the list is n.
22+
1 <= k <= n <= 105
23+
0 <= Node.val <= 100
24+
"""
25+
# Definition for singly-linked list.
26+
# class ListNode:
27+
# def __init__(self, val=0, next=None):
28+
# self.val = val
29+
# self.next = next
30+
class Solution:
31+
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
32+
left,right = head,head
33+
for _ in range(k-1):
34+
right = right.next
35+
r = right
36+
while right.next:
37+
left = left.next
38+
right = right.next
39+
r.val,left.val = left.val,r.val
40+
return head

0 commit comments

Comments
 (0)