您的位置:首页 > 其它

leetcode题解-61. Rotate List

2017-06-27 21:43 351 查看
61,题目:

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值可能比链表总长度还要大,这就会带来一定的麻烦。为了方便起见,我们可以先遍历链表,获取链表的总长度,然后将链表首尾相连编成一个环,这样做的好处是我们可以很容易获得要反转的位置,然后在该处将链表截断即可。代码入下:

public ListNode rotateRight1(ListNode head, int k) {
if(head==null||head.next==null||k==0) return head;

//获取链表的总长度
ListNode index=head; int len=1;
while(index.next!=null)
{index=index.next; len++;}
//将链表首尾相连形成环
index.next=head;

//找到需要截断的位置,因为k可能大于链表总长度。所以这里使用取余操作
for(int i=0;i<len-k%len;i++)
{
index=index.next;
}
//将该处截断,指向空指针即可
ListNode result=index.next;
index.next=null;
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: