常见算法 - 链表相关:反转列表指定范围内的节点

常规思路,范围内反转列表

(leetcode92):

public class L92ReverseLinkedListII {

	
	public static ListNode reverseBetween(ListNode head, int m, int n) {
	   
		if(head == null){
			return null;
		}
		ListNode temp = new ListNode(0);
		temp.next = head;
		ListNode startPre = temp;
		for(int i = 1; i < m;i++){
			startPre = startPre.next;
		}
		ListNode start =startPre.next;
		ListNode next = start.next;
		
		for(int i = 0; i < n-m; i++){
			start.next = next.next;
			next.next = startPre.next;
			startPre.next = next;
			next = start.next;
		}
		return temp.next;
	}
}

猜你喜欢

转载自blog.csdn.net/b9x__/article/details/80217658