Leetcode61.旋转链表

题目链接:61.旋转链表

思路:右移k个位置就是将链表右边的k个节点放到表头。那么就让1个指针从表头先走k-1步(算上表头节点此时一共经过k个节点),然后再让一个指针从表头出发,此时两个指针含有k个节点,当先走的指针到达链表尾部,那么两个指针所包含的节点就是要右移到表头的节点。

代码:

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

*执行用时: 1 ms
内存消耗: 37.9 MB
*

原文地址:https://www.cnblogs.com/liuyongyu/p/14220391.html