92. 反转链表 II + 有左右边界的翻转链表 + 翻转

92. 反转链表 II

LeetCode_92

题目描述

解法一:穿针引线法-模拟的思路

  1. 首先确定一个左边界start表示翻转开始的起始点。
  2. 在左右边界之间不断修改next指针指向下一个结点。
  3. 当遍历到右边界的下一个字符时开始翻转这一整段的链表。
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode pre = null, now = head;
        int cnt = 0;
        ListNode start = null, end = null;
        while(now != null){
            cnt++;
            ListNode temp = now.next;
            if(cnt == left){
                start = now;
                now.next = pre;
            }else if(cnt == right+1){
                if(start.next != null){
                    start.next.next = pre;
                    start.next = now;
                }else{
                    start.next = now;
                    head = pre;
                }
                return head;
            }else if(cnt > left && cnt <= right){
                now.next = pre;
            }
            pre = now;
            now = temp;
        }
        if(cnt == right){
            if(start.next != null){
                start.next.next = pre;
                start.next = null;
            }else{
                start.next = null;
                head = pre;
            }
        }
        return head;
    }
}

方法二:类似于插入结点的方法穿针引线

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode vnode = new ListNode(-1);//虚拟结点
        vnode.next = head;

        ListNode pre = vnode;
        //让pre指向翻转区间的前一个结点
        for(int i=0; i<left-1; i++){
            pre = pre.next;
        }
        ListNode current = pre.next;
        //依次翻转区间的结点,不断把下一个结点移动到开始区间的第一个位置
        for(int i=0; i<right - left; i++){
            ListNode temp = current.next;
            current.next = temp.next;
            temp.next = pre.next;
            pre.next = temp;//注意以上两行不能写成pre.next = temp; temp.next = current;因为这里的current不一定是最接近起始点的位置,current会改变的
        }
        return vnode.next;
    }
}
posted @ 2021-03-15 20:52  Garrett_Wale  阅读(90)  评论(0编辑  收藏  举报