Advertisement
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 *left, *right, *curr;
- int len=0;
- curr = head;
- while(curr){
- len++;
- if(len == k) left=curr;
- curr = curr->next;
- }
- curr=head;
- for(int i=1; i<=len; i++){
- if(len-k+1 == i) right = curr;
- curr = curr->next;
- }
- swap(left->val, right->val);
- return head;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement