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.

 

思路一: 确定需要右循环的开头节点和尾部节点,然后和原先的head节点了解起来

java代码:

  1. public ListNode rotateRight(ListNode head, int n) {
  2. if(n<=0) return head;
  3. if(head==null || head.next==null) return head;
  4. int len = 0;
  5. ListNode p=head;
  6. while(p!=null && p.next!=null) {
  7. len++;
  8. p=p.next;
  9. }
  10. len++;
  11. ListNode end = p;  //尾节点
  12. n = n%len;
  13. if(n==0) return head;
  14. p = head;
  15. ListNode pre = null;
  16. n = len - n;
  17. int i=0;
  18. while(i<n) {
  19. i++;
  20. pre = p;
  21. p=p.next;  //需要循环的头结点
  22. }
  23. pre.next = null;
  24. end.next = head;
  25. head = p;
  26. return head;
  27. }
posted @ 2014-07-24 00:42  purejade  阅读(85)  评论(0)    收藏  举报