共计 845 个字符,预计需要花费 3 分钟才能阅读完成。
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
难度:medium
题目:反转从 m 到 n 的链表元素。一次遍历。
思路:记录 m 及 m 之前的位置,然后使用头插法。
Runtime: 2 ms, faster than 97.09% of Java online submissions for Reverse Linked List II.Memory Usage: 36.9 MB, less than 0.95% of Java online submissions for Reverse Linked List II.
/**
* 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 (m == n) {
return head;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode ptr = head, prevMPtr = dummyHead, tailPtr = head;
for (int i = 1; i <= n; i++) {
ListNode node = ptr;
ptr = ptr.next;
if (i < m) {
prevMPtr = node;
} else if (i == m) {
tailPtr = node;
node.next = null;
} else {
node.next = prevMPtr.next;
prevMPtr.next = node;
}
}
tailPtr.next = ptr;
return dummyHead.next;
}
}