Rotate List —— LeetCode
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
.
题目大意:给一个链表和一个非负整数k,把链表向右循环移位k位。
解题思路:踩了个坑,k有可能比链表的长度还长,比如长度为3的链表,k=2000000000,所以开始需要遍历一下链表算出长度,k%=len,然后就是两个pointer一个先走k步,另一个再走,最后把末尾的next节点设为head,新head就是慢指针指向的节点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null||k == 0){ return head; } int fast = k; ListNode fastNode = head; ListNode slowNode = head; ListNode pre = slowNode; int len = 0; while(fastNode!=null){ len++; fastNode=fastNode.next; } fast %= len; fastNode = head; if(fast == 0){ return head; } while(fastNode!=null&&fast-->0){ fastNode = fastNode.next; } while(fastNode!=null){ fastNode = fastNode.next; pre = slowNode; slowNode = slowNode.next; } ListNode newHead = new ListNode(0); newHead.next = slowNode; pre.next = null; while(slowNode.next!=null){ slowNode = slowNode.next; } slowNode.next = head; return newHead.next; } }