链表指定起始终点反转(Leetcode92)

2018-11-11  本文已影响0人  zhouwaiqiang

题目

解题思路

解题源代码

/**
 * 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 front = new ListNode(0);
        front.next = head;
        ListNode pre = front, index = head;//index用于遍历,pre用于表示反转链表m的前一个链表节点
        ListNode reverseLast = null;//反转链表后的最后一个节点,也是反转前的第一个链表指针
        int count = 0;
        while (index != null) {
            count++;
            if (count == m) {
                reverseLast = index;//暂存
                ListNode temp = index;
                index = index.next;
                temp.next = null;
                pre.next = temp;
                continue;
            }
            if (count < m) {
                pre = index;//更新父节点
            }
            //采用头插法实现反转
            if (count > m && count <= n) {
                ListNode temp = index;
                index = index.next;
                temp.next = pre.next;
                pre.next = temp;
                continue;
            }
            if (count == n+1) {
                reverseLast.next = index;
                break;
            }
            index = index.next;
        }
        return front.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读