package top.ssyuan.medium;import java.util.Stack;import top.ssyuan.Util;import top.ssyuan.easy.Lesson206;/** * 92. Reverse Linked List II * Medium * <p> * Given the head of a singly linked list and two integers left and right where left <= right, * reverse the nodes of the list from position left to position right, and return the reversed list. * <p> * <p> * Example 1: * <p> * <p> * Input: head = [1,2,3,4,5], left = 2, right = 4 * Output: [1,4,3,2,5] * Example 2: * <p> * Input: head = [5], left = 1, right = 1 * Output: [5] * <p> * <p> * Constraints: * <p> * The number of nodes in the list is n. * 1 <= n <= 500 * -500 <= Node.val <= 500 * 1 <= left <= right <= n */public class Lesson92 { public static void main(String[] args) { Lesson92 lesson = new Lesson92(); ListNode head = lesson.genLinkList(10); lesson.printLink(head); head = new Solution1().reverseBetween(head, 1, 3); Util.println(""); lesson.printLink(head); } private void printLink(ListNode head) { ListNode node = head; while (node != null) { Util.print(node.val + "->"); node = node.next; } } private ListNode genLinkList(int count) { if (count < 1) return null; ListNode head = new ListNode((int) (Math.random() * 100)); ListNode curNode = head; for (int i = 1; i < count; i++) { curNode.next = new ListNode((int) (Math.random() * 100)); curNode = curNode.next; } return head; } //Definition for singly-linked list. private class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } private static class Solution1 { public ListNode reverseBetween(ListNode head, int left, int right) { if (head == null || left > right) { return null; } Stack<ListNode> stack = new Stack<>(); ListNode node = head; ListNode pre = head; ListNode next = null; int index = 0; while (node != null) { if (index < left - 1) { pre = node; } if (index >= left - 1 && index < right) { stack.push(node); } if (index >= right) { next = node; break; } node = node.next; index++; } ListNode head2 = stack.pop(); node = head2; while (!stack.empty()) { node.next = stack.pop(); node = node.next; } pre.next = head2; if (node != null) { node.next = next; } return left == 1 ? head2 : head; } } private static class Solution2 { public ListNode reverseBetween(ListNode head, int left, int right) { if (head == null || left >= right) { return null; } ListNode node = head; ListNode pre = null; ListNode tmp = node; while (node != null) { tmp = node; node = node.next; tmp.next = pre; pre = tmp; } return tmp; } }}