LeetCode 1721: Swapping Nodes in a Linked List

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).
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode first=head,second=head,fast=head,slow=head;
while(k!=1){
fast = fast.next;
k--;
}
first = fast;
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
second = slow;
k = slow.val;
slow.val = first.val;
first.val = k;
return head;
}
}

To connect and collaborate ping me:
LinkedIn
Twitter
GitHub

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store