[leetcode]61. Rotate List

忘记哪一题了,反正和前面有一题很像,挺简单的

Solution 1: 利用循环链表O(n)

int dis=count-k%count;
利用这个式子,将问题转换为–找新的head node即可

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
       //if head is null or k=0, we simply return head;
        if(head==null||k==0)return head;
 
        ListNode p=head;
        int count=0;
        //p points to the last node when loop ends
        while(p.next!=null){
            count++;
            p=p.next;
        }
        // in the loop above, when p points to the last node, p.next==null
        // so the last node didn't count++, we now manually count++;
        count++;
       //we calculate the distance we need to move to the new head
        int dis=count-k%count;
        
        // make the last node point to head, which makes this list a  cicular list
        p.next=head;
        //we use q to move from head
        ListNode q=head;
     
     //q now moves to a  node exactly before the new head node 
        for(int i=0;i<dis-1;i++){
            q=q.next;
        }
        //p now points to the new head node 
        p=q.next;
        // so now q is the last node of the new list
        // we set the next field of the last node as null
        q.next=null;
	//return the new head 
        return p;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_36869329/article/details/85220832