1721. Swapping Nodes in a Linked List
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
vals = []
while head:
vals.append(head.val)
head = head.next
head = answer = ListNode()
vals[k-1], vals[-k] = vals[-k], vals[k-1]
for i in range(len(vals)):
answer.val = vals[i]
if i != len(vals) - 1:
answer.next = ListNode()
answer = answer.next
return head
O(N)
(N: head의 길이)O(N)
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
cur_node = head
for _ in range(k-1):
cur_node = cur_node.next
left_swap_node = cur_node
right_swap_node = head
while cur_node.next:
cur_node = cur_node.next
right_swap_node = right_swap_node.next
left_swap_node.val, right_swap_node.val = right_swap_node.val, left_swap_node.val
return head
O(N)
O(1)