描述
给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
您在真实的面试中是否遇到过这个题?
样例
给出链表1->2->3->4->5->null和k=2
给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
您在真实的面试中是否遇到过这个题?
样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
程序
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode * rotateRight(ListNode * head, int k) {
// write your code here
//版本一
/*
if(head == NULL || k == 0 || head->next == NULL)
return head;
ListNode *cur = head;
int size = 0;
while(cur){//计算链表得到全部长度
size++;
cur = cur->next;
}
//cout << "总长度 " << size << endl;
if(k % size != 0){
cur = head;
int curList = size - k % size;//断开处的位置
//cout << "断开处 " << curList << endl;
for(int i = 1; i < curList; i++){//找到断开处
cur = cur->next;
}
ListNode *afterList = cur->next;//后半段链表的头结点
//cout << "后半段链表的头结点 " << afterList->val << endl;
cur->next = NULL;//前半段链表末尾指向NULL
//cout << "前半段链表的尾结点 " << cur->val << endl;
cur = afterList;
while(cur->next){//找到后半段的最后一个节点
cur = cur->next;
}
cur->next = head;//让最后一个节点指向前半段的头结点
return afterList;
}
else{
return head;
}
*/
//版本二
if(head == NULL)
return head;
int len = 0;
for(ListNode *node = head; node != NULL; node = node->next)
len++;
k = k%len;
ListNode *fast = head;
for(int i = 0; i < k; i++){
fast = fast->next;
}
ListNode *slow = head;
while(fast->next != NULL){
slow = slow->next;
fast = fast->next;
}
fast->next = head;
head = slow->next;
slow->next = NULL;
return head;
}
};