描述
给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
分析:
首先,遍历一遍链表得到链表长度len和原链表最后一个结点pNode。然后k=k%len,如果k为0,表示移动后为本身,直接返回head即可。
以样例为例子,新链表头为原链表倒数第k个结点,即正数第len-k+1个结点,新链表尾为正数第len-k个结点,通过一次遍历得到新链表头cur和新链表为pre;
最后,pre.next=null; pNode.next=head;return cur;
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if(head==null) return null;
int len=1;
ListNode pNode=head;
while(pNode.next!=null){
len++;
pNode=pNode.next;
} //pNode此时指向最后一个元素
if(k%len==0) return head;
k=k%len;
//找到倒数第k个结点,即正数第len-k+1个
ListNode cur=head;
ListNode pre=null;
int index=len-k;
while(index>0){
pre=cur;
cur=cur.next;
index--;
} //pre是新链表最后一个元素,cur是新链表头
pre.next=null;
pNode.next=head;
return cur;
}