Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- ListNode* swapNodes(ListNode* head, int k) {
- ListNode* temp = head;
- int n=0;
- while(temp!=nullptr)
- {
- n++;
- temp=temp->next;
- }
- int ans = n-k+1;
- temp = head;
- ListNode* firstpoin;
- ListNode* secondpoin;
- int c=1;
- while(temp!=nullptr)
- {
- if(c==k)
- {
- firstpoin = temp;
- }
- if(c==ans)
- {
- secondpoin = temp;
- }
- temp = temp->next;
- c++;
- }
- int tmp;
- tmp = secondpoin->val;
- secondpoin->val = firstpoin->val;
- firstpoin->val = tmp;
- return head;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment