Thursday, October 21, 2021

[LeetCode] Swapping Nodes in a Linked List

Problem: 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:

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
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]
Input: head = [1], k = 1
Output: [1]
Input: head = [1,2], k = 1
Output: [2,1]
Input: head = [1,2,3], k = 2
Output: [1,2,3]

Constraints:

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


Approach: It's a straight forward problem to solve. You can understand the approach by just looking at the implementation.


Implementation in C#:

    public ListNode SwapNodes(ListNode head, int k) 

    {

        if (head == null)

        {

            return head;

        }

        ListNode node = head;

        // Get the kth node from the start

        for (int i = 1; i < k; ++i)

        {

            node = node.next;

        }        

        ListNode swapNode1 = node;

        ListNode swapNode2 = head;

        // Get the kth node from the end

        while (node.next != null)

        {

            swapNode2 = swapNode2.next;

            node = node.next;

        }

        int temp = swapNode1.val;

        swapNode1.val = swapNode2.val;

        swapNode2.val = temp;

        return head;

    }


Complexity: O(n)

No comments:

Post a Comment