forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1721-swapping-nodes-in-a-linked-list.cpp
43 lines (39 loc) · 1.11 KB
/
1721-swapping-nodes-in-a-linked-list.cpp
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
33
34
35
36
37
38
39
40
41
42
43
/*
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).
Ex. Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Time : O(N)
Space : O(1)
*/
/**
* 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) {
if(head == NULL || head -> next == NULL)
return head;
ListNode *ptr = head, *beg = head, *end = head;
int a = 0;
while(ptr != NULL) {
a++;
if(a == k)
beg = ptr;
if(a >= k + 1)
end = end -> next;
ptr = ptr -> next;
}
int temp = beg -> val;
beg -> val = end -> val;
end -> val = temp;
return head;
}
};