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->NULLand 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; }
结果:
相关文章推荐
- leetcode 61.Rotate List
- 【Leetcode】61. Rotate List
- 【LeetCode】61. Rotate List
- Leetcode 61. Rotate List
- 【leetcode每日一题】61.Rotate List
- LeetCode(61) Rotate List
- Leetcode 61 Rotate List
- Leetcode ☞ 61. Rotate List
- LeetCode 61. Rotate List
- LeetCode 61: Rotate List
- LeetCode 61. Rotate List
- leetcode-61. Rotate List
- LeetCode 61 Rotate List
- leetcode 61. Rotate List
- leetcode 61. Rotate List
- Leetcode-61. Rotate List
- leetcode 61:Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- LeetCode | 61. Rotate List