思路:遍历ListNode,存入list中,然后反向
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
List<ListNode> list=f(head, new ArrayList<ListNode>());
list.get(m-1).next=list.get(n-1).next;
for (int i = n-1; i >=m; i--) {
list.get(i).next=list.get(i-1);
}
if (m!=1) {
list.get(m-2).next=list.get(n-1);
return list.get(0);
}else {
return list.get(n-1);
}
}
public List<ListNode> f(ListNode head,List<ListNode> list){
if (head!=null) {
list.add(head);
list=f(head.next,list);
}
return list;
}
}
本文详细介绍了如何使用迭代方法遍历链表并将其反转的过程。通过将节点依次存入列表,然后反向链接,实现了对指定区间内的链表元素进行反转的操作,确保了算法的高效性和简洁性。
944

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



