Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b0140ce

Browse files
committed
Add solution 92.
1 parent 0a60380 commit b0140ce

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for a singly-linked list.
3+
* class ListNode {
4+
* public $val = 0;
5+
* public $next = null;
6+
* function __construct($val) { $this->val = $val; }
7+
* }
8+
*/
9+
class Solution {
10+
11+
/**
12+
* @param ListNode $head
13+
* @param Integer $m
14+
* @param Integer $n
15+
* @return ListNode
16+
*/
17+
function reverseBetween($head, $m, $n) {
18+
$dummy = new ListNode(-1);
19+
$pre; $cur;
20+
$connection; $tail; // tail points to the last node of the reversed sub-list
21+
$pre = $dummy;
22+
$dummy->next = $head;
23+
24+
// this loop aims to find the connection node and the first node to be reversed.
25+
for($i=0; $i<$m-1; $i++) {
26+
$pre = $pre->next;
27+
}
28+
$connection = $pre;
29+
$tail = $cur = $pre->next;
30+
31+
$temp;
32+
// this loop is just like the similar problem(https://leetcode.com/problems/reverse-linked-list/)
33+
for($i=$m; $i<=$n; $i++) {
34+
$temp = $cur->next;
35+
$cur->next = $pre;
36+
$pre = $cur;
37+
$cur = $temp;
38+
}
39+
40+
// adjust the connection points
41+
$tail->next = $cur;
42+
$connection->next = $pre;
43+
return $dummy->next;
44+
}
45+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /