Leetcode92. 反转链表 II
92. 反转链表 II
Difficulty: 中等
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
Solution
Language: java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode t = head, pre = null;
for(int i=1; i<left; i++){
pre = t;
t = t.next;
}
ListNode end = t, start = t;
for(int i=0; i<right-left; i++){
ListNode tmp = t.next;
t.next = tmp.next;
tmp.next = start;
start = tmp;
}
if(pre == null) head = start;
else pre.next = start;
return head;
}
}