ID | Title | Difficulty | |
---|---|---|---|
Loading... |
92. Reverse Linked List II
Medium
LeetCode
Linked List
Problem
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev = dummy;
// 1. 找到翻转起始点
for(int i = 1; i < m; i++){
prev = prev.next;
}
ListNode curr = prev.next;
// 2. 翻转
// 重点在prev并不移动
for(int i = m; i < n; i++){
ListNode next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
return dummy.next;
}
}
按 <- 键看上一题!
91. Decode Ways
按 -> 键看下一题!
93. Restore IP Addresses