- 注意不是翻转链表
- 给出1->2->3->4->5->NULL 以及 k = 2, 返回 4->5->1->2->3->NULL.
- 将链表从右边数第k个开始后面的全部交换到链表的左侧。例如对于1,2,3,4,5,6 和 k = 2,就有交换之后的节点就是5,6,1,2,3,4。注意这里的k可能会超过链表的长度大小。
- 做法是首先可以计算链表的长度len,再将链表连成一个环状。接着从链表起始数len - k将链表断开,那么就完成了旋转,代码如下:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return NULL;
ListNode * p1 = head;
int count = 0;
while(p1->next){
count++;
p1 = p1->next;
}
count++;
int len = count - k%count;
if(len == 0)
return head;
p1->next = head;
p1 = head;
for(int i = 1; i < len; ++i){
p1 = p1->next;
}
ListNode * ret = p1->next;
p1->next = NULL;
return ret;
}
};
public static void main(String[] args) {
print p = new print();
ListNode n = createList();
System.out.println(p.rotateList(n, 0).val);
}
public static ListNode createList(){
ListNode node = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(3);
ListNode node3 = new ListNode(4);
ListNode node4 = new ListNode(4);
node.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
return node;
}
ListNode getPartion(ListNode begin, ListNode end) {
if (begin == end || end == null)
return null;
ListNode p = begin, q = begin.next;
while (q != end.next) {
if (q.val < begin.val) {
p = p.next;
swap(p, q);
}
q = q.next;
}
swap(begin, p);
return p;
}