Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
思路:
类似于Reverse Linked List I, 思路自然而然的是:在遇到起始点的时候,断开其前面的链表连接,因此flag == m - 1时断开。之后在后面的子链表进行反转,停止条件为flag == n - 1,即类似于pivot.next == null。(加头节点便于操作)
Solution
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
int flag = 0;
ListNode k = new ListNode(0);
k.next = head;
if (m == n){
return head;
}else{
ListNode ps = k;
while (flag != m - 1){
k = k.next;
flag += 1;
}
ListNode pn = k.next;
ListNode pivot = pn;
k.next = null;
ListNode front = null;
while (flag != n - 1){
front = pivot.next;
pivot.next = pivot.next.next;
front.next = pn;
pn = front;
flag += 1;
}
k.next = pn;
return ps.next;
}
}
}
网友评论