题目来源:https://leetcode.com/problems/reverse-linked-list-ii/
问题描述
92. Reverse Linked List II
Medium
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
------------------------------------------------------------
题意
翻转链表第m个节点和第n个节点之间的节点
------------------------------------------------------------
思路
自己在纸上画画就会了。解释一下代码里的几个指针吧。
cur: 当前节点
pre: 当前节点的前驱节点
tail: 保存第m个节点,将来在被翻转的链表尾
/* 以下两个节点用于链表翻转过程的暂存 */
ahead: 当前节点的后继节点
tmp: 当前节点的副本
------------------------------------------------------------
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n || head == null)
{
return head;
}
int cnt = 1;
ListNode pre = null, ptr = head;
ListNode ahead = null, tail = null, tmp = null;
while (true)
{
if (cnt >= m && cnt < n)
{
if (cnt == m)
{
tail = ptr;
ptr = ptr.next;
ahead = ptr.next;
ptr.next = tail;
}
else
{
tmp = ptr;
ptr = ahead;
ahead = ahead.next;
ptr.next = tmp;
}
}
else if (cnt == n)
{
if (pre != null)
{
pre.next = ptr;
tail.next = ahead;
return head;
}
else
{
tail.next = ahead;
return ptr;
}
}
else
{
pre = ptr;
ptr = ptr.next;
}
cnt++;
}
}
}