61. 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.

一刷
题解:
两种思路,先遍历一遍求出链表的长度len, 用k-len得到距离头部的距离,然后找到需要reverse的节点的前一个节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || k<0) return null; 
        ListNode node = head;
        int len = 1;
        while(node.next!=null){
            node = node.next;
            len++;
        }
        
        node.next = head;
        
        k = len-k %len;
        while(k>0){
            node = node.next;
            k--;
        }
        
        head = node.next;
        node.next = null;
        return head;
    }
}

第二个思路,快慢指针, 得到需要reverse为head的前一个节点.

二刷:
与一刷思路相同,先求得整个链表的长度len,避免k过大。真正的k为k%len. 然后求得第i-k个点(表头为1),那么该点的next需要被移至head

public ListNode rotateRight(ListNode head, int n) {
    if (head==null||head.next==null) return head;
    ListNode dummy=new ListNode(0);
    dummy.next=head;
    ListNode fast=dummy,slow=dummy;

    int i;
    for (i=0;fast.next!=null;i++)//Get the total length 
        fast=fast.next;
    
    for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
        slow=slow.next;
    
    fast.next=dummy.next; //Do the rotation
    dummy.next=slow.next;
    slow.next=null;
    
    return dummy.next;
}

你可能感兴趣的:(61. Rotate List)