【LeetCode】 92. Reverse Linked List II 反转链表 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/reverse-linked-list-ii/
题目描述:
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
题目大意
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
解题方法
1、找出第 m 个元素的前一个元素并记录第 m - 1 和第 m 个元素
2、反转从第 m 个元素到第 n 个元素
3、把三段元素拼接起来
/**
* 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) {
ListNode pre = null;
ListNode res = head;
for (int i = 1; i < m - 1; i++) {
head = head.next;
}
ListNode first = head;
ListNode tail = head;
if (m == 1) {
} else {
head = head.next;
tail = head;
}
for (int i = m; i <= n; i++) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
if (m > 1) first.next = pre;
tail.next = head;
if (m == 1) return pre;
return res;
}
}
执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 37.3 MB, 在所有 Java 提交中击败了 8.70% 的用户