题目:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
有一个单链表,需要每次反转k个节点,最后返回修改后的链表。
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
如果链表的节点个数不是k的倍数,那么不调整链表的顺序。
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
/**
* 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 == NULL || head->next==NULL || k==0 || k==1)
return head;
//整个链长度
int len=getLen(head);
//可以反转轮数
int rc=len/k;
//给这个链添加一个头结点
ListNode phead=ListNode(-1);
phead.next=head;
//变换形式(k=3,将需要变幻的节点插入到一段逆致序列的最前面):
//ph->1->2->3->4->5 ; ph->2->1->3->4->5 ; ph->3->2->1->4->5 ;
//ph->3->2->1->4->5(之后的借点数小于k,所以顺序不变)
ListNode *p,*c,*q;
p=&phead;
c=p->next;
q=c->next;
//进行rci轮反转
while(rc>0)
{
for(int i=0;i<k-1;i++)
{
c->next=q->next;
q->next=p->next;
p->next=q;
q=c->next;
}
//c未指向链末时
if(c->next!=NULL)
{
p=c;
c=q;
q=q->next;
}
rc--;
}
return phead.next;
}
//计算链长
int getLen(ListNode * head)
{
ListNode * p=head;
int l=0;
if(p==NULL)
return 0;
while(p)
{
l++;
p=p->next;
}
return l;
}
}; // 创建链表
ListNode* CreateList(int A[],int n)
{
ListNode *head = NULL;
if(n <= 0){
return head;
}//if
head = new ListNode(A[0]);
ListNode *p1 = head;
for(int i = 1;i < n;i++){
ListNode *node = new ListNode(A[i]);
p1->next = node;
p1 = node;
}//for
return head;
}
int main()
{
Solution solution;
//vector<ListNode *> vecs;
int A[] = {1,2};
//int B[] = {3,5,8,10,11,12};
//int C[] = {6,10,13};
//int D[] = {15,16,17,23};
ListNode* head1 = CreateList(A,2);
//ListNode* head2 = CreateList(B,6);
//ListNode* head3 = CreateList(C,3);
//ListNode* head4 = CreateList(D,4);
//vecs.push_back(head1);
//vecs.push_back(head2);
//vecs.push_back(head3);
//vecs.push_back(head4);
//ListNode *head = solution.mergeKLists(vecs);
<span style="white-space:pre"> </span> ListNode* head = solution.reverseKGroup(head1, 2) ;
// 输出
ListNode *p = head;
while(p){
cout<<p->val<<" ";
p = p->next;
}
}