nikunjsoni

1721

Mar 16th, 2021
62
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* swapNodes(ListNode* head, int k) {
  14.         ListNode *left, *right, *curr;
  15.         int len=0;
  16.         curr = head;
  17.         while(curr){
  18.             len++;
  19.             if(len == k) left=curr;
  20.             curr = curr->next;
  21.         }
  22.         curr=head;
  23.         for(int i=1; i<=len; i++){
  24.             if(len-k+1 == i) right = curr;
  25.             curr = curr->next;
  26.         }
  27.         swap(left->val, right->val);
  28.         return head;
  29.     }
  30. };
RAW Paste Data