leetcode-92-reverse-linked-list-ii

Description

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ mn ≤ length of list.

Example:

1
2
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

####

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n) return head;

ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pNode = dummy;
ListNode start = head;
for (int i = 1; i < m; i ++ ) {
pNode = start;
start = start.next;
}for (int i = 0; i < n - m; i ++ ) {

ListNode temp = start.next;
start.next = temp.next;
temp.next = pNode.next;
pNode.next = temp;
}
return dummy.next;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×