您的位置:首页 > 其它

leetcode_61_Rotate List

2015-02-01 15:20 393 查看

描述:

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
.

思路:

本文的题意就是循环将后面的n个结点移动到前面去,所以,n有可能是大于链表的长度的,这是一个小小的陷阱。然后就是很简单的细节了,有点脑残,提交了好多次。

代码:

public ListNode rotateRight(ListNode head, int n) {
if(n<=0||head==null)
return head;
int len=1,index=0;
ListNode pListNode=head,qListNode=null,tailListNode=null;
while(pListNode.next!=null)
{
len++;
pListNode=pListNode.next;
}
tailListNode=pListNode;
n=n%len;
if(n==0)
return head;
index=len-n;
index--;
pListNode=head;
for(int i=0;i<index;i++)
{
pListNode=pListNode.next;
}
qListNode=pListNode.next;
pListNode.next=null;
pListNode=head;
head=qListNode;
tailListNode.next=pListNode;
return head;
}


结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: