原题地址:https://leetcode-cn.com/problems/reverse-linked-list-ii/
题目描述:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
代码:
/**
* 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(head == null || head.next == null || m == n) return head;
ListNode slow = head, pre = null;
for(int i = 1; i < m; i ++)
{
pre = slow;
slow = slow.next;
}
ListNode cur = slow;
for(int i = 1; i <= n - m; i ++)
{
ListNode t = slow.next.next;
slow.next.next = cur;
cur = slow.next;
slow.next = t;
}
if(pre != null)
{
pre.next = cur;
return head;
}
return cur;
}
}
本文介绍了一种在一趟扫描内反转链表中指定区间[m,n]的算法。通过一次遍历,利用指针操作实现节点之间的链接调整,达到区间内元素顺序的反转。适用于LeetCode上的一道经典链表题目。
701

被折叠的 条评论
为什么被折叠?



