Advertisement
Guest User

Grokking #204

a guest
Jan 5th, 2022
74
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2.  
  3.   public ListNode swapNodes(ListNode head, int k) {
  4.    
  5.     ListNode n1 = null;
  6.     ListNode n2 = null;
  7.    
  8.     ListNode first = head;
  9.     ListNode second = head;
  10.     for (int i = 1; i <= k; i++) {
  11.      
  12.       if (i == k) {
  13.         n1 = second;
  14.       }
  15.      
  16.       second = second.next;
  17.     }
  18.    
  19.     while (second != null) {
  20.       first = first.next;
  21.       second = second.next;
  22.     }
  23.    
  24.     n2 = first;
  25.    
  26.     // swap n1 and n2 values
  27.     int tmp = n1.val;
  28.     n1.val = n2.val;
  29.     n2.val = tmp;
  30.    
  31.     return head;
  32.    
  33.   }
  34. }
  35.  
Advertisement
RAW Paste Data Copied
Advertisement