给出一个链表,一次翻转 k 个指针节点,并返回修改后的链表。
k 是一个正整数,并且小于等于链表的长度。如果指针节点的数量不是 k 的整数倍,那么最后剩余的节点应当保持原来的样子。
你不应该改变节点的值,只有节点位置本身可能会改变。
题目应当保证,仅使用恒定的内存。
例如,
给定这个链表:1->2->3->4->5
当 k = 2时,应当返回: 2->1->4->3->5
当 k = 3时,应当返回: 3->2->1->4->5
详见:https://leetcode.com/problems/reverse-nodes-in-k-group/description/
实现语言:Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null||k==1){
return head;
}
ListNode dummy=new ListNode(-1);
ListNode pre=dummy;
ListNode cur=head;
dummy.next=head;
int i=0;
while(cur!=null){
++i;
if(i%k==0){
pre=reverseOneGroup(pre,cur.next);
cur=pre.next;
}else{
cur=cur.next;
}
}
return dummy.next;
}
private ListNode reverseOneGroup(ListNode pre,ListNode next){
ListNode last=pre.next;
ListNode cur=last.next;
while(cur!=next){
last.next=cur.next;
cur.next=pre.next;
pre.next=cur;
cur=last.next;
}
return last;
}
}
实现语言:C++
/**
* 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||k==1)
{
return head;
}
ListNode* dummy=new ListNode(-1);
ListNode* pre=dummy;
ListNode* cur=head;
dummy->next=head;
int i=0;
while(cur)
{
++i;
if(i%k==0)
{
pre=reverseOneGroup(pre,cur->next);
cur=pre->next;
}
else
{
cur=cur->next;
}
}
return dummy->next;
}
ListNode* reverseOneGroup(ListNode* pre,ListNode* next)
{
ListNode* last=pre->next;
ListNode* cur=last->next;
while(cur!=next)
{
last->next=cur->next;
cur->next=pre->next;
pre->next=cur;
cur=last->next;
}
return last;
}
};
参考:https://www.cnblogs.com/grandyang/p/4441324.html