题解 | #牛群旋转#
牛群旋转
https://www.nowcoder.com/practice/5137e606573843e5bf4d8ea0d8ade7f4
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode rotateLeft (ListNode head, int k) {
// write code here
if(head==null||head.next==null||k==0){
return head;
}
int len=1;
ListNode cur=head;
while(cur.next!=null){
len++;
cur=cur.next;
}
cur.next=head;
k=k%len;
int first=len-k+1;
while(first-->0){
if(first==0){
ListNode temp=cur;
cur=cur.next;
temp.next=null;
break;
}
cur=cur.next;
}
return cur;
}
}
本题知识点分析:
1.链表遍历
2.双指针
本题解题思路分析:
- 首先获取到整个链表的长度
length,观察到每移动length次,链表就会变成原来的样子。 - 用k对length取模得到n,移动这n次即可得到答案。
- 用双指针找到倒数第n个点,把他作为头节点,把前面的节点插入到链表末尾就能得到最终结果。

