Reverse Linked List II
Reverse a linked list from position m to n.
Reverse a linked list from position m to n.
Notice
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
ExampleGiven 1->2->3->4->5->NULL
, m = 2
and n = 4
, return 1->4->3->2->5->NULL
.
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Given 1->2->3->4->5->NULL
, m = 2
and n = 4
, return 1->4->3->2->5->NULL
.
分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | /** * 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 nhead = new ListNode(- 1 ); ListNode h = nhead; h.next = head; ListNode l1 = head, l2; int count = 1 ; while (count < m){ h = l1; l1 = l1.next; count++; } //h l1 //1->2<-3->4->5->NULL ListNode last = null ; while (count <= n){ ListNode tmp = l1.next; l1.next = last; last = l1; l1 = tmp; count++; } //h L l1 //1->2<-3<-4 5->NULL h.next.next = l1; h.next = last; return nhead.next; } } |