【LeetCode】92. 反转链表 II(JAVA)

原题地址: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;
            
        
    }
}

递归解法参考

发布了110 篇原创文章 · 获赞 4 · 访问量 9323

猜你喜欢

转载自blog.csdn.net/rabbitsockx/article/details/104675897