Python版本
class Solution: def reverseBetween(self , head , m , n ): # write code here res=[] while head: res.append(head.val)//此处理论可以保存head,但实际会超时,此题目不太严谨,仅仅通过交换节点的val,就能通过 head=head.next //测试案例,而题目本意,是反转区间节点而不是反转val值 res=res[0:m-1]+res[m-1:n][::-1]+res[n:] first=ListNode(0) head1=first for i in res: temp=ListNode(i) head1.next=temp head1=temp return first.next
java版本
import java.util.*; import java.util.Iterator; /* * 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) { // write code here List<Integer> list=new ArrayList<>(); ListNode head1=head; while(head1!=null){ list.add(head1.val); head1=head1.next; } List<Integer> tt=new ArrayList<>(); tt.addAll(list.subList(0,m-1)); tt.addAll(rev(list.subList(m-1,n))); tt.addAll(list.subList(n,list.size())); Iterator iter=list.iterator(); ListNode first=new ListNode(0); ListNode head2=first; while(iter.hasNext()){ ListNode temp=new ListNode((int)iter.next()); head2.next=temp; head2=temp; } return first.next; } public static List rev(List list){ Collections.reverse(list); return list; } }