LeetCode 92. 反转链表 II
Posted 菜鸡的世界
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 92. 反转链表 II相关的知识,希望对你有一定的参考价值。
题目连接
题目分析
题目要求我们用一趟扫描完成旋转,我们只需要先把[m,n]这段区间内的链表定位了就容易做了。当我们完成定位后就是普通的三指针反转链表
代码实现
/**
* 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) {
ListNode fast = head;
int count = 1;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
while(fast != null){
if(count < m){
slow = slow.next;
}
fast = fast.next;
count++;
if(count == n){
ListNode tail = fast.next;
fast.next = null;
ListNode node = slow.next;
slow.next = null;
fast = node;
ListNode cur = node;
ListNode post = null;
while(fast != null){
fast = fast.next;
cur.next = post;
post = cur;
cur = fast;
}
slow.next = post;
node.next = tail;
return dummy.next;
}
}
return head;
}
}
以上是关于LeetCode 92. 反转链表 II的主要内容,如果未能解决你的问题,请参考以下文章