旋转链表

题目描述:给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:双指针法
  • 首先,如果head为null或者head只有一个节点,直接返回head;
  • 遍历链表head得到链表的长度为length,根据k % length算得toJump,toJump为实际需要多少位挪到链表前面,如果toJump为0,说明旋转后不需要挪动,直接返回head,如果toJump大于0,则初始化2个节点first和last分别指向头结点,然后利用双指针法,得到需要挪的最后几位,具体处理过程如下:
    • 首先将last移动到链表的第toJump位;
    • 然后同时移动first和last节点,直到last的next不为空为止。
  • 最后移动到last的next为空,此时last即为原链表的最后一个节点,first的next节点为新的头结点,此时,初始化newHead为first的next节点,然后将first的next置空,first为新链表的最后一个节点,然后将last指向原链表的头结点head,最后返回newHead即为旋转后的链表。
  1. public class LeetCode_061 {
  2. public static ListNode rotateRight(ListNode head, int k) {
  3. if (head == null || head.next == null) {
  4. return head;
  5. }
  6. ListNode cur = head;
  7. // 链表的长度
  8. int length = 0;
  9. while (cur != null) {
  10. length++;
  11. cur = cur.next;
  12. }
  13. // 需要将倒数 toJump 位挪到 head 节点前面
  14. int toJump = k % length;
  15. if (toJump == 0) {
  16. return head;
  17. }
  18. ListNode first = head, last = head;
  19. while (toJump > 0) {
  20. last = last.next;
  21. toJump--;
  22. }
  23. while (last.next != null) {
  24. first = first.next;
  25. last = last.next;
  26. }
  27. ListNode newHead = first.next;
  28. first.next = null;
  29. last.next = head;
  30. return newHead;
  31. }
  32. public static void main(String[] args) {
  33. ListNode head = new ListNode(0);
  34. head.next = new ListNode(1);
  35. head.next.next = new ListNode(2);
  36. ListNode listNode = rotateRight(head, 4);
  37. while (listNode != null) {
  38. System.out.print(listNode.val + " ");
  39. listNode = listNode.next;
  40. }
  41. }
  42. }

【每日寄语】 只要你今天再多努力一下,那个未来可以像星星一样闪闪发光的人就是你呀!