DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Swap Kth node from start and end of a LinkedList

Problem

TC: O(n)
SC: (1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapNodes(ListNode head, int k) {
        ListNode slow = head;
        ListNode fast = head;
        ListNode prev = null;
        while(k-->0){
            prev = fast;
            fast = fast.next;
        }
        while(fast!=null){
            slow = slow.next;
            fast = fast.next;
        }
        int temp = slow.val;
        slow.val = prev.val;
        prev.val = temp;
        return head;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)