classSolution{public ListNode rotateRight(ListNode head,int k){if(k ==0|| head == null || head.next == null)return head;
ListNode first = head.next;if(first.next == null){if(k%2==0){return head;}else{
head.next = null;
first.next = head;
head = first;return head;}}int j =2;while(first.next != null){
first = first.next;
j++;}
k = k%j;for(int i=0;i<k;i++){
first = head.next;
ListNode second = first.next;while(second.next != null){
first = second;
second = first.next;}
first.next = null;
second.next = head;
head = second;}return head;}}
解法二:想法比较巧妙,把链表变成一个封闭的环,再判断在哪里断开。
classSolution{public ListNode rotateRight(ListNode head,int k){// base casesif(head == null)return null;if(head.next == null)return head;// close the linked list into the ring
ListNode old_tail = head;int n;for(n =1; old_tail.next != null; n++)
old_tail = old_tail.next;
old_tail.next = head;// find new tail : (n - k % n - 1)th node// and new head : (n - k % n)th node
ListNode new_tail = head;for(int i =0; i < n - k % n -1; i++)
new_tail = new_tail.next;
ListNode new_head = new_tail.next;// break the ring
new_tail.next = null;return new_head;}}
作者:LeetCode
链接:https://leetcode-cn.com/problems/rotate-list/solution/xuan-zhuan-lian-biao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。