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.
https://oj.leetcode.com/problems/reverse-linked-list-ii/
思路:链表操作。
public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode newHead = new ListNode(-1); newHead.next = head; ListNode p = newHead; for (int i = 0; i < m - 1; i++) { p = p.next; } ListNode pre = p; ListNode start = p.next; for (int i = 0; i < n - m; i++) { p = start.next; start.next = p.next; p.next = pre.next; pre.next = p; } return newHead.next; } public static void main(String[] args) { ListNode head = ListUtils.makeList(new int[] { 1, 2, 3, 4, 5 }); ListUtils.printList(head); head = new Solution().reverseBetween(head, 4, 5); ListUtils.printList(head); } }
第二遍记录:
reverse链表的方法,每次添加在pre的后面。