旋转链表
题目
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
解析重点
1.我们观察就可以知道旋转k个数,即将k%n个后面的数挪到前面即可。即将链表从n-k%n处分开,将后面的部分拼接到前面。
2.那么这里我们主要涉及到4个node,原来的first=node[1]、end=node[n],改变后的first1=node[n-k%n+1]、end1=node[n-k%n]。因此,我们需要计算出n->链表长度,
及end、first1、end1。然后将几个node挪动即可。
java代码
1 | /** |