题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if (m == n) {
            return head;
        }
        ListNode tmp = head;
        ListNode head1 = null;
        ListNode tail = null;
        ListNode pre = null;
        ListNode cur;
        ListNode next;
        int index = 1;
        while (tmp != null) {
            if (index == m - 1) {
                head1 = tmp;
                tmp = tmp.next;
            } else if (index == m ) {
                tail = tmp;
                cur = tmp;
                next = tmp.next;
                cur.next = pre;

                pre = cur;
                tmp = next;

            } else if (index > m && index < n) {
                cur = tmp;
                next = tmp.next;
                cur.next = pre;

                pre = cur;
                tmp = next;

            } else if (index == n) {
                cur = tmp;
                next = tmp.next;
                cur.next = pre;

                tail.next = next;
                if (head1 != null) {
                    head1.next = cur;
                } else {
                    head = cur;
                }
            } else {
                tmp = tmp.next;
            }
            index++;
        }
        return head;
    }
}
  1. 循环整个链表
  2. 弄三个变量记住上一个节点,当前节点,下一个节点
  3. 再弄两个变量记住当前区间范围
  4. 最后将当前区间连接到原来的链表
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务