61. 旋转链表

image.png

获取到链表的总长度值
示例2中如果k=3的话 实际上整个链表并不需要移动
示例2中k=4 只是把链表最后一个移到头部
示例1k=2 是把尾部两个元素移到头部
移动的索引位置=链表长度-(k%链表长度)

  1. package main
  2. import "fmt"
  3. type ListNode struct {
  4. Val int
  5. Next *ListNode
  6. }
  7. func rotateRight(head *ListNode, k int) *ListNode {
  8. if head==nil||head.Next==nil||k==0 {
  9. return head
  10. }
  11. count :=1
  12. cursor := head
  13. for cursor.Next!=nil{
  14. count++
  15. cursor =cursor.Next
  16. }
  17. //// 相等不需要移动
  18. k =k%count
  19. if k==0 {
  20. return head
  21. }
  22. //当前是尾结点 // 头尾相连 循环链表
  23. cursor.Next = head
  24. // 找到需要分割的节点
  25. /*
  26. 1 2 3 4 第0次
  27. 4 1 2 3 第1次
  28. 3 4 1 2 第2次
  29. */
  30. l :=count-(k%count)
  31. pre := head
  32. for i:=0;i<l-1;i++{
  33. pre = pre.Next
  34. }
  35. newHead := pre.Next
  36. pre.Next = nil
  37. return newHead
  38. }
  39. func main() {
  40. one :=&ListNode{
  41. Val: 1,
  42. }
  43. two :=&ListNode{
  44. Val: 2,
  45. }
  46. three :=&ListNode{
  47. Val: 3,
  48. }
  49. four :=&ListNode{
  50. Val: 4,
  51. }
  52. five :=&ListNode{
  53. Val: 5,
  54. }
  55. one.Next = two
  56. two.Next = three
  57. three.Next= four
  58. four.Next = five
  59. h:=rotateRight(one,2)
  60. for h!=nil{
  61. fmt.Println(h.Val)
  62. h =h.Next
  63. }
  64. }

image.png