1721. Swapping Nodes in a Linked List
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: ListNode* swapNodes(ListNode* head, int k) { ListNode* lastNode = head; ListNode* target1 = head; ListNode* target2 = head; for(int i = 1; i < k; i++) { lastNode = lastNode->next; target1 = target1->next; } while(lastNode->next != nullptr) { lastNode = lastNode->next; target2 = target2->next; } swap(target1->val, target2->val);
return head; } };
|