import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
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 || n < m || n == 0) {
return head;
}
ListNode reverseNode = new ListNode(0);
reverseNode.next = head;
ListNode pre = reverseNode;
for (int i = 1; i < m; i++) {
pre = pre.next;
}
ListNode curr = pre.next;
while (n-- > m) {
ListNode temp = curr.next;
curr.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
return reverseNode.next;
}
}
该博客主要讲解了如何使用Java实现指定范围内的双向链表反转。通过创建一个虚拟头节点简化操作,并使用迭代方式完成反转。代码中定义了一个ListNode类,包含整型值和next指针。Solution类的reverseBetween方法接收链表头节点、开始位置m和结束位置n,返回反转后的链表头节点。
1489

被折叠的 条评论
为什么被折叠?



