Rotate List

来源:互联网 发布:微屏软件科技有限公司 编辑:程序博客网 时间:2024/05/15 01:57

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.


思路:首先算length,然后k%length,然后fast slow, fast先走k步,然后一起走,最后找到newhead,然后连起来,注意k==0,return head;

/**  * 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 || head.next == null) return head;         int len = 0;         ListNode node = head;         while(node!=null) {             node = node.next;             len++;         }         k = k%len;         if(k == 0)  return head;                  ListNode slow = head;         ListNode fast = head;         int step = k;         while(step>0){             fast = fast.next;             step--;         }         while(fast != null && fast.next!=null){             slow = slow.next;             fast = fast.next;         }         ListNode newhead = slow.next;         slow.next = null;         fast.next = head;         return newhead;     } }


0 0