Reverse a linked list from position m to n.
Notice
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Example
Given 1->2->3->4->5->NULL
, m = 2
and n = 4
, return1->4->3->2->5->NULL
.
Challenge
Reverse it in-place and in one-pass
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param ListNode head is the head of the linked list * @oaram m and n * @return: The head of the reversed ListNode */ public ListNode reverseBetween(ListNode head, int m , int n) { // write your code ListNode fakehead = new ListNode(0); fakehead.next = head; ListNode end1 = fakehead; for(int i = 1; i < m; i++) end1 = end1.next; ListNode head2 = end1.next; end1.next = null; ListNode end2 = head2; for(int i = 0; i < n - m; i++) end2 = end2.next; ListNode head3 = end2.next; end2.next = null; head2 = reverse(head2); end1.next = head2; end2 = head2; while(end2.next != null) end2 = end2.next; end2.next = head3; return fakehead.next; } public ListNode reverse(ListNode head){ if(head == null || head.next == null) return head; ListNode prev = head; ListNode curr = head.next; ListNode next = head.next.next; head.next = null; while(next != null){ curr.next = prev; prev = curr; curr = next; next = next.next; } curr.next = prev; return curr; } }
时间: 2024-10-12 21:04:42