-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseAndRemove.php
60 lines (50 loc) · 1.3 KB
/
ReverseAndRemove.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {
/**
* @param ListNode $head
* @param Integer $n
* @return ListNode
*/
function removeNthFromEnd($head, $n) {
$newHead = $newList = new ListNode($head->val);
$head = $this->reverse($head, null);
$i = 1;
while($head){
if($i == $n) {
$remove = $head->next;
$head = $remove ;
}
if(!is_null($head->val)){
$newNode = new ListNode($head->val);
$newList->next = $newNode;
$newList = $newList->next ;
}
$head = $head->next;
$i++;
}
$head = $this->reverse($newHead->next, null);
return $head;
}
/**
* @param ListNode $head
* @param ListNode $newHead
* @return ListNode
*/
function reverse($head, $newHead) {
if($head == null) return $newHead;
$next = $head->next;
$head->next = $newHead;
return $this->reverse($next, $head);
}
}