Reverse a linked list from positionMToN. Do it in-place and in one-pass.
For example:
Given1->2->3->4->5->NULL
,M= 2 andN= 4,
Return1->4->3->2->5->NULL
.
Note:
GivenM,NSatisfy the following condition:
1 ≤M≤N≤Length of list.
Question:
As shown in, there are several important variables:
Prev records the listnode in the previous position of M ~ 5. After this paragraph is reversed, the next pointer of Prev should be set to the first pointer of the reverse sequence;
Head records the first listnode of the sublist to be reversed;
Kepeler records the last listnode of the sublist to be reversed;
There is a special case, as shown in:
When the first listnode of the sequence to be reversed is the head node of the linked list, the prev pointer is empty. At this time, the head node of the linked list becomes the node pointed to by the above kepeler, so it should be processed separately at the end.
Code 21 ~ Locate the position of Prev and head in a loop of 25 rows, 27 ~ Locate the location of the kepeler in a loop of 31 rows, 33 ~ The for loop of 39 rows reverses the linked list with the specified range of the linked list. Row 41: determines whether the header node of the reverse sequence is the last node in the list to be reversed-kepeler. If yes, kepeler is returned. Otherwise, the original linked list header node is returned.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode reverseBetween(ListNode head, int m, int n) {14 int HeadNodes = 0;15 ListNode answer = head;16 ListNode prev = null;17 18 if(head == null || m >= n)19 return answer;20 21 while(HeadNodes+1 < m){22 prev = head;23 head = head.next;24 HeadNodes++;25 }26 27 ListNode kepeler = head;28 while(HeadNodes+1 < n){29 kepeler = kepeler.next;30 HeadNodes++;31 }32 33 for(int i = 0;i < n-m;i++){34 ListNode temp = head.next;35 head.next = kepeler.next;36 kepeler.next = head;37 38 head = temp;39 }40 41 if(prev == null)42 return kepeler;43 else{44 prev.next = kepeler;45 return answer;46 }47 }48 }