给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
我的思路:想借助栈来存储需要反转的链表,记录下来left-1的节点和right+1的节点,翻转后重新接上即可
代码如下:
public class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { if (left == right){ return head; } ListNode res = new ListNode(); ListNode preRes = res; Stack<ListNode> stack = new Stack<>(); int i = 1; while (head != null){ if (i <= left - 1){ res.next = head; res = res.next; } if (i >= left && i <= right){ stack.push(head); } if (i > right){ break; } head = head.next; i++; } while (!stack.isEmpty()){ ListNode node = stack.pop(); res.next = node; res = node; } res.next = head; return preRes.next; } }