题目描述:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example: Given1->2->3->4->5->NULL, m = 2 and n = 4,
return1->4->3->2->5->NULL.
Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
解题思路:
- 首先理解题意,题目的意思就是说,给定一个链表和两个参数,在原地将给定参数之间的链表节点反转
- 首先想到的方法是把给定参数范围内的链表取出来,进行反转操作,然后再接回去
- 2 中的解题方法稍微有一点粗鲁,这道题的主要考察点,我认为是将链表反转,故采用连续反转的另一个方法,具体看代码
代码如下:
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode prestart = newHead;
ListNode start = head;
// 找到开始反转的起始节点
for(int i = 1; i < m; i++){
prestart = start;
start = start.next;
}
// 反转的链表长度有多长,就操作多少次,这个操作的核心要义是每次将后面一个节点往前提
// 示例:2 -> 3 -> 4
// 3 -> 2 -> 4
// 4 -> 3 -> 2
for(int i = 0; i < n - m; i++){
ListNode temp = start.next;
start.next = temp.next;
temp.next = prestart.next;
prestart.next = temp;
}
return newHead.next;
}