题意:

image.png

解题思路:

  1. 思路:时间复杂度是 O(n)
  2. 1. 计算链表长度,走到链表尾部;
  3. 2. 首尾相连;
  4. 3. 移动 k 个位置,找到结束点;
  5. 4. 断开结束点;
  6. 5. 返回结果值;

图示:

未命名文件 (12).jpg

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. /**
  11. * @param ListNode $head
  12. * @param Integer $k
  13. * @return ListNode
  14. */
  15. function rotateRight($head, $k) {
  16. $p = $head;
  17. $length = 1;
  18. while ($p->next != null) {
  19. $p = $p->next;
  20. $length++;
  21. }
  22. //头尾相连
  23. $p->next = $head;
  24. //如果k大于length会造成跳多圈的情况,所以可以采用取模避免重复
  25. for ($i = 1; $i < $length - ($k % $length); $i++) {
  26. $head = $head->next;
  27. }
  28. $res = $head->next;
  29. $head->next = null;
  30. return $res;
  31. }
  32. function rotateRight1($head, $k) {
  33. $p = $head;
  34. $length = 1;
  35. while ($p->next != null) {
  36. $p = $p->next;
  37. $length++;
  38. }
  39. //尾部指向头部,形成环
  40. $p->next = $head;
  41. //如果k大于length会造成跳多圈的情况,所以可以采用取模避免重复
  42. $l = $length - ($k % $length);
  43. //跳几步,找到结束点
  44. $newEnd = $head;
  45. for ($i = 1; $i < $l; $i++) {
  46. $newEnd = $newEnd->next;
  47. }
  48. $newHead = $newEnd->next;
  49. //断开
  50. $newEnd->next = null;
  51. return $newHead;
  52. }
  53. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func rotateRight(head *ListNode, k int) *ListNode {
  9. if head == nil || head.Next == nil || k == 0 {
  10. return head
  11. }
  12. p := head
  13. length := 1
  14. for p.Next != nil {
  15. length++
  16. p = p.Next
  17. }
  18. p.Next = head
  19. p = head
  20. for i := 1; i < (length - k % length); i++ {
  21. p = p.Next
  22. }
  23. res := p.Next
  24. p.Next = nil
  25. return res
  26. }