Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fc9edd4

Browse files
committed
o(n) time and o(1) space using two pointers.
1 parent 2399591 commit fc9edd4

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)

AltStyle によって変換されたページ (->オリジナル) /