61 旋转链表

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode rotateRight(ListNode head, int k) {
  13. if (head == null)
  14. return head;
  15. int listLength = getListLength(head);
  16. k = k % listLength;
  17. // 构造头节点
  18. ListNode pHead = new ListNode(-1);
  19. pHead.next = head;
  20. ListNode p = head;
  21. // 先将链表断开,在按照尾插法插入到第一个链表后面
  22. for (int i = 1; i <= listLength - k - 1; i++)
  23. p = p.next;
  24. // 将链表断开
  25. ListNode q = p.next;
  26. p.next = null;
  27. // q进行尾插法
  28. ListNode temp = pHead;
  29. while (q != null) {
  30. p = q.next;
  31. q.next = temp.next;
  32. temp.next = q;
  33. q = p;
  34. temp = temp.next;
  35. }
  36. return pHead.next;
  37. }
  38. private int getListLength(ListNode head) {
  39. // 获取链表长度
  40. int length = 0;
  41. for (ListNode p = head; p != null; p = p.next)
  42. ++length;
  43. return length;
  44. }
  45. }