1721-swapping-nodes-in-a-linked-list

Try it on leetcode

Description

You are given the head of a linked list, and an integer k.

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).

 

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Example 2:

Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

Solution(Python)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        return self.constantspace(head, k)

    # Time Complexity: O(n)
    # Space Complexity: O(n)
    def extraspace(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        arr = []
        cur = head

        while cur:
            arr.append(cur.val)
            cur = cur.next

        n = len(arr)
        arr[k - 1], arr[n - k] = arr[n - k], arr[k - 1]

        newHead = ListNode()
        cur = newHead
        for i in range(n):
            cur.next = ListNode(arr[i])
            cur = cur.next

        return newHead.next

    # Time Complexity: O(n)
    # Space Complexity: O(1)
    def constantspace(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        cur = head
        N1 = None
        n = 0
        while cur is not None:
            if n == k - 1:
                N1 = cur
            cur = cur.next
            n += 1

        cur = head
        i = 0
        while cur is not None:
            if i == n - k:
                N2 = cur
                break
            cur = cur.next
            i += 1
        N1.val, N2.val = N2.val, N1.val

        return head