jayati

Swapping Nodes in a Linked List

Jan 21st, 2023
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  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* temp = head;
  15.         int n=0;
  16.         while(temp!=nullptr)
  17.         {
  18.             n++;
  19.             temp=temp->next;
  20.         }
  21.         int ans = n-k+1;
  22.         temp = head;
  23.         ListNode* firstpoin;
  24.         ListNode* secondpoin;
  25.         int c=1;
  26.         while(temp!=nullptr)
  27.         {
  28.             if(c==k)
  29.             {
  30.                 firstpoin = temp;
  31.             }
  32.             if(c==ans)
  33.             {
  34.                 secondpoin = temp;
  35.             }
  36.             temp = temp->next;
  37.             c++;
  38.         }
  39.         int tmp;
  40.         tmp = secondpoin->val;
  41.         secondpoin->val = firstpoin->val;
  42.         firstpoin->val = tmp;
  43.        
  44.         return head;
  45.     }
  46.    
  47. };
Advertisement
Add Comment
Please, Sign In to add comment