标签:
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.
解题思路:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { //iterative //base case if (head == null || head.next == null || m < 1 || m >= n) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode cur = head; //move m-1 to the node before reverse start int count = 1; while (count < m) { pre = cur; cur = cur.next; count++; } ListNode beforeReverse = pre; ListNode startReverse = cur; while (count <= n) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; count++; } beforeReverse.next = pre; startReverse.next = cur; return dummy.next; } }
Reference:
Leetcode 92. Reverse Linked List II
标签:
原文地址:http://www.cnblogs.com/anne-vista/p/5551671.html