LeetCode Rotate List
2015-01-12 21:23
351 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
使用两个指针,第一个先走k步,然后第二个开始走,知道第一个走到最后一个。
这样第二个指针正好是 len-k个,它就是新链表的最后一个元素。
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
使用两个指针,第一个先走k步,然后第二个开始走,知道第一个走到最后一个。
这样第二个指针正好是 len-k个,它就是新链表的最后一个元素。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { ListNode temp = head; if(temp==null) return temp; int len=0; while (temp != null) { ++len; temp = temp.next; } n = n % len; ListNode fast=head; ListNode slow = head; for (int i = 0; i < n; i++) { fast = fast.next; } while (fast.next != null) { fast=fast.next; slow = slow.next; } fast.next=head; head = slow.next; slow.next = null; return head; } }
相关文章推荐
- 【leetcode】Rotate List
- LeetCode:Rotate List
- Leetcode: Rotate List
- leetcode 61. Rotate List
- [LeetCode]61. Rotate List
- leetcode之Rotate List
- [LeetCode]--61. Rotate List
- leetcode Rotate List
- Leetcode rotate list
- leetcode 61. Rotate List
- [LeetCode] Rotate List
- leetcode JAVA Rotate List 难度系数3 3.20
- LeetCode 60 Rotate List
- [leetcode] Rotate List
- leetcode[61]Rotate List
- LeetCode 61 — Rotate List(C++ Java Python)
- leetcode之Rotate List
- leetcode 70: Rotate List
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- LeetCode(61) Rotate List