-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap_nodes_in_pairs.php
42 lines (35 loc) · 986 Bytes
/
swap_nodes_in_pairs.php
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
<?php
/**
* Swap Nodes in Pairs
* @link https://leetcode.com/problems/swap-nodes-in-pairs
*
* Approach:
* Take current,next nodes and just swap them, before swap store pointer to the next node of next node in temp variable
* Also keep track of previous node, so after swap we can point it to the swapped one
*
* Time Complexity - O(n)
* Space Complexity - O(1)
*/
class Solution {
public function swapPairs($head) {
if (!$head || !$head->next) {
return $head;
}
$previous = null;
$newHead = $head->next;
$current = $head;
$next = $head->next;
while ($next) {
$tmp = $next->next;
$next->next = $current;
$current->next = $tmp;
if ($previous) {
$previous->next = $next;
}
$previous = $current;
$current = $current->next;
$next = $current->next;
}
return $newHead;
}
}