反转链表中的一部分

/**
 * 反转链表中的一部分,给出索引[m,n]索引从1开始
 * 比如链表是这样的1->2->3->4->5->6,反转[2,5],变成了1->5->4->3->2->6
 * @return
 */
public class Test7 {
    
    

	static ListNode tmp;
	
	static ListNode reverse(ListNode head, int m, int n ) {
    
    
		if (m == 1) {
    
    
			return reverseN(head, n);
		}
		ListNode last = reverse(head.next, m - 1, n - 1);
		head.next = last;
		return head;
	}
	
	static ListNode reverseN(ListNode head, int n) {
    
    
		if (n == 1) {
    
    
			tmp = head.next;
			return head;
		}
		ListNode last = reverseN(head.next, n - 1);
		head.next.next = head;
		head.next = tmp;
		return last;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_36986015/article/details/113744424