Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
题目大意就是给你一个链表,再给你一个数字k,当链表未逆置过的节点数不小于k时,逆置前未逆置过的k个节点,否则节点不变,
我的思路就是用别的来存节点指针,算出链表长度,来确定要进行逆置的次数,每逆置一次,长度减k,当长度小于k时就结束逆置
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || !head->next || k==1)
return head;
vector<ListNode*> p;
ListNode* temp = head;
while(temp){//把节点指针存入vector
p.push_back(temp);
temp = temp->next;
}
int length = p.size();
if (length < k)//链表长度小于k时直接返回
return head;
int need = length;
int left = 0;
int right = k-1;
while(need >= k){
for(int i=left,j=right;i<j;i++,j--)//逆置前k个节点
swap(p[i],p[j]);
need -= k;//链表长度减k
left += k;//后移k个单位,准备下一次逆置
right += k;
}
head = new ListNode(0);
temp = head;
for(int i=0;i<length;i++){
temp->next = p[i];
temp = temp->next;
}
if(temp->next)//有些情况下最后一个节点的next域不为NULL,导致链表中出现循环而出错
temp->next = NULL;
return head->next;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || !head->next || k==1)
return head;
ListNode* result = new ListNode(0);
ListNode* temp,*box,*sub = result;
while(head){
temp = head->next;
for (int i=2;i<k;i++){
if(temp)
temp = temp->next;
else{
sub->next = head;
return result->next;
}
}
if (!temp){
sub->next = head;
return result->next;
}
box = head;
for (int i=0;i<k;i++){
temp = head;
head = head->next;
temp->next = sub->next;
sub->next = temp;
}
sub = box;
}
return result->next;
}
};
比第一种快了16ms。