[leetcode]Rotate List

新博文地址:[leetcode]Rotate List

 

Rotate List

 

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

 将链表翻转,我不知道OJ上怎么处理k>length的情况,我是直接取余了

 

    public ListNode rotateRight(ListNode head, int n) {
    	if(head == null || n == 0){
    		return head;
    	}
    	int length = 1;
    	ListNode tail = head;//tail指向尾节点
    	while(tail.next != null){
    		length++;
    		tail = tail.next;
    	}
    	if(n == length){
    		return head;
    	}else{
    		n %= length;
    		if(n == 0){
    			return head;
    		}
    	}
    	int count = length - n;
    	ListNode newTail = head;
    	for(int i = 0 ; i < count - 1; newTail = newTail.next,i++);
    	ListNode newHead = newTail.next;
    	tail.next = head;
    	newTail.next = null;
    	return newHead;   	
    }

 

 

你可能感兴趣的:(LeetCode)