File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Author: King, wangjingui@outlook.com
3
+ Date: Jan 2, 2015
4
+ Problem: Reverse Linked List II
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/reverse-linked-list-ii/
7
+ Notes:
8
+ Reverse a linked list from position m to n. Do it in-place and in one-pass.
9
+ For example:
10
+ Given 1->2->3->4->5->NULL, m = 2 and n = 4,
11
+ return 1->4->3->2->5->NULL.
12
+ Note:
13
+ Given m, n satisfy the following condition:
14
+ 1 <= m <= n <= length of list.
15
+
16
+ Solution: in-place & one-pass.
17
+ */
18
+
19
+ /**
20
+ * Definition for singly-linked list.
21
+ * public class ListNode {
22
+ * int val;
23
+ * ListNode next;
24
+ * ListNode(int x) {
25
+ * val = x;
26
+ * next = null;
27
+ * }
28
+ * }
29
+ */
30
+ public class Solution {
31
+ public ListNode reverseBetween (ListNode head , int m , int n ) {
32
+ ListNode dummy = new ListNode (-1 );
33
+ dummy .next = head ;
34
+ ListNode first = dummy ;
35
+ for (int i = 0 ; i < m - 1 ; ++i ) first = first .next ;
36
+ ListNode cur = first .next ;
37
+ for (int i = 0 ; i < n - m ; ++i ) {
38
+ ListNode move = cur .next ;
39
+ cur .next = move .next ;
40
+ move .next = first .next ;
41
+ first .next = move ;
42
+ }
43
+ return dummy .next ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments