【leetcode刷题笔记】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.


 

题解:首先注意一点是n可以比链表的length大。例如链表1->2,n=3,那么执行3次rotate的过程如下:

第一次:2->1;

第二次:1->2;

第三次:2->1;

那么我们是不是就要模拟了呢?答案是不用,只要用n = n%length就可以在一次遍历中完成转换。

还是快慢指针的思想,fast指针比slow指针快n+1步,当fast指针到达尾部时,slow指针的next元素就是新的链表头。还需要一个tail指针作为fast指针的前驱,并在最后利用tail指针把前半段链表链接起来。

代码如下:

 1 /**

 2  * Definition for singly-linked list.

 3  * public class ListNode {

 4  *     int val;

 5  *     ListNode next;

 6  *     ListNode(int x) {

 7  *         val = x;

 8  *         next = null;

 9  *     }

10  * }

11  */

12 public class Solution {

13     private int getLength(ListNode head){

14         int answer = 0;

15         while(head != null){

16             answer++;

17             head = head.next;

18         }

19         

20         return answer;

21     }

22     

23     public ListNode rotateRight(ListNode head, int n) {

24         if(head == null || head.next == null)

25             return head;

26         

27         int length = getLength(head);

28         if(n == 0)

29             return head;

30         n = n % length;

31         

32         ListNode dummy = new ListNode(0);

33         dummy.next = head;

34         ListNode slow = dummy;

35         ListNode fast = head;

36         for(int i = 0;i < n;i++)

37                 fast = fast.next;

38         

39         ListNode tail = fast;

40         while(fast != null){

41             slow = slow.next;

42             tail = fast;

43             fast = fast.next;

44         }

45         tail.next = dummy.next;

46         dummy = slow.next;

47         slow.next = null;

48         return dummy;

49     }

50 }

你可能感兴趣的:(LeetCode)