leetcode题解-61. Rotate List
2017-06-27 21:43
351 查看
61,题目:
本题是将链表在某处进行翻转,但问题是k值可能比链表总长度还要大,这就会带来一定的麻烦。为了方便起见,我们可以先遍历链表,获取链表的总长度,然后将链表首尾相连编成一个环,这样做的好处是我们可以很容易获得要反转的位置,然后在该处将链表截断即可。代码入下:
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; }
相关文章推荐
- 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
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- leetcode——61——Rotate List
- [LeetCode] 61. Rotate List
- [Leetcode 61, Medium] Rotate List
- leetcode[61]Rotate List
- [leetcode 61] Rotate List
- leetcode-61. Rotate List
- leetcode 61. Rotate List
- [Leetcode 57] 61 Rotate List
- LeetCode 61. Rotate List2.