Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
解题思路:
指针操作即可,旋转参考Java for LeetCode 025 Reverse Nodes in k-Group JAVA实现如下:
static public ListNode reverseBetween(ListNode head, int m, int n) { ListNode result = new ListNode(0); result.next = head; if (m >= n || m <= 0) return result.next; head = result; for (int i = 0; i < m - 1; i++) head = head.next; Stack<Integer> stk = new Stack<Integer>(); ListNode temp = head.next; for (int i = 0; i <= n - m; i++) if (temp != null) { stk.push(temp.val); temp = temp.next; } if (stk.size() == n - m + 1) { while (!stk.isEmpty()) { head.next = new ListNode(stk.pop()); head = head.next; } head.next = temp; } return result.next; }