力扣0092——反转链表II

反转链表II

难度:中等

题目描述

给你单链表的头指针 head 和两个整数 leftright ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表

示例1

输入: head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

示例2

输入: head = [5], left = 1, right = 1
输出:[5]

题解

由于没有提及修改原链表节点,那么可以直接修改值,具体方法如下

  • 快慢指针,慢指针指向left,快指针指向right,将两个值交换
  • 将慢指针右移,快指针移动到right - 1,继续交换

当左右指针会面,即可结束,得到最终答案

想法代码

public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val; 
        this.next = next;
    }
}
class Solution
{
    public static void Main(String[] args)
    {
        Solution solution = new Solution();
        ListNode head = new ListNode(1)
        {
            next = new ListNode(2)
            {
                next = new ListNode(3)
                {
                    next = new ListNode(4)
                    {
                        next = new ListNode(5) 
                    }
                }
            }
        };
        int left = 2;
        int right = 4;
        ListNode ans = solution.ReverseBetween(head, left, right);
        while (ans != null)
        {
            Console.Write(ans.val + " ");
            ans = ans.next;
        }
    }

    public ListNode ReverseBetween(ListNode head, int left, int right)
    {
        if (left == right)
        {
            return head;
        }
        ListNode ans = head;
        ListNode slow = head;
        for (int i = 0; i < left - 1; i++)
        {
            slow = slow.next;
        }
        for (int i = left; i < right; i++)
        {
            ListNode fast = head;
            for (int j = 0; j < right - 1; j++)
            {
                fast = fast.next;
            }
            int temp = fast.val;
            fast.val = slow.val;
            slow.val = temp;
            slow = slow.next;
            right--;
        }
        return ans;
    }
}
          slow = slow.next;
            right--;
        }
        return ans;
    }
}

你可能感兴趣的:(算法进修,leetcode,链表,算法)