问题:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULL
and k = 2
, return 4->5->1->2->3->NULL
. [1,2,3,4,5,6,7,8,9,10] k=3,---->[8,9,10,1,2,3,4,5,6,7]
解决:
① 这道旋转链表的题和 Rotate Array 旋转数组 很类似,因为链表的值不能通过下标来访问,只能一个一个的走。我刚开始想到的就是用快慢指针来解,快指针先走k步,然后两个指针一起走,当快指针走到末尾时,慢指针的下一个位置是新的顺序的头结点,这样就可以旋转链表了。但是需要注意的有很多:
首先一个就是当原链表为空时,直接返回NULL;
还有就是当k大于链表长度和k远远大于链表长度时该如何处理,我们需要首先遍历一遍原链表得到链表长度n,然后k对n取余,这样k肯定小于n,就可以用上面的算法了。
/**
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { //15ms public ListNode rotateRight(ListNode head, int k) { if(head == null) return null; int len = 0; ListNode cur = head; while(cur != null){ len ++; cur = cur.next; } k %= len; ListNode slow = head; ListNode fast = head; for (int i = 0;i < k ;i ++ ) {//fast先前进k步 if(fast != null) fast = fast.next; } if(fast == null) return head; while(fast.next != null){ fast = fast.next; slow = slow.next; } fast.next = head; fast = slow.next; slow.next = null; return fast; } }② 使用一个指针,原理是先遍历整个链表获得链表长度n,然后此时把链表头和尾链接起来,在往后走n - k % n个节点就到达新链表的头结点前一个点,这时断开链表即可。
/**
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { //16ms public ListNode rotateRight(ListNode head, int k) { if(head == null) return null; int len = 1; ListNode cur = head; while(cur.next != null){ len ++; cur = cur.next; } cur.next = head; int m = len - k % len;//新的尾节点的位置 for (int i = 0;i < m ;i ++ ) { cur = cur.next; } ListNode newHead = cur.next; cur.next = null; return newHead; } }