题解 | 链表内指定区间反转
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ public ListNode reverseBetween (ListNode head, int m, int n) { if(head == null || head.next == null || m == n) { return head; } Stack<ListNode> stack = new Stack<>(); int x = 0; ListNode preNode = head; ListNode sufNode = null; ListNode tln = preNode; if(m == 1) { stack.push(head); } for(int i = 1;;i++){ ListNode listNode = tln.next; tln = listNode; // 下一个节点为空,直接跳出循环 if(listNode == null) { break; } if(i < m - 1) { preNode = listNode; } else if(i >= m - 1 && i <= n - 1) { preNode.next = null; stack.push(listNode); } else { sufNode = listNode; break; } } stack.peek().next = null; ListNode reverListNode = stack.pop(); ListNode tempNode = reverListNode; while(!stack.isEmpty()) { ListNode listNode = stack.pop(); listNode.next = null; tempNode.next = listNode; tempNode = listNode; } // 头部截取的地方追加反转后的节点 if(m > 1) { preNode.next = reverListNode; } else { head = reverListNode; } // 追加尾巴 tempNode.next = sufNode; return head; } }