Pages

Monday, September 15, 2025

Leetcode 1721. Swapping Nodes in a Linked List

 /**

 * 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) {    
        // Step 1: Find length of the list
        ListNode curr = head;
        int n = 0;
        while(curr != null) {
            n++;
            curr = curr.next;
        }

        // Step 2: Find kth node from the start and kth node from the end
        ListNode first = head;
   
        for(int i=1; i<k; i++) {
            first = first.next;
        }

        ListNode second = head;
        for(int j=1; j<n-k+1; j++) {
            second = second.next;
        }

        int temp = first.val;
        first.val = second.val;
        second.val = temp;
       
        return head;
    }
}

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...