Topic:
Given A linked list, reverse the nodes of a linked list K at a time and return to its modified list.
If the number of nodes is isn't a multiple of k then left-out nodes in the end should remain as it is.
You could not alter the values of the nodes, only nodes itself is changed.
Only constant memory is allowed.
For example,
Given this linked list:1->2->3->4->5
For k = 2, should return:2->1->4->3->5
For k = 3, should return:3->2->1->4->5: Given a list and a number k, with K as a circular section, reverse the elements in the linked list, if the remaining length is less than K, then the last part does not reverse.
Calculate the length of the linked list, divided by the length of the cycle, and count the number of times the linked list is reversed.
The list of links in each loop section is reversed with three pointers to maintain.
When the operation is the first loop section, you need to change the value of the head pointer.
After each cycle section is reversed, the ph and PE two pointers are used to maintain the pointer connection between the links.
/** * 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) {ListNode *p1,*p2,*p3,*ph,*pe;
if (head==null) return NULL;
int n=0,i,j;
P1=head;
if (k==1) return head;
while (p1) {n++;
p1=p1->next;
} P1=head;
p2=p1->next;
if (p2) p3=p2->next;
for (I=0;i<n/k;++i) {for (j=1;j<k;++j) {p2->next=p1;
P1=P2;
P2=P3;
if (p3) p3=p3->next;
} if (i==0) {ph=head;
ph->next=p2;
PE=P2;
HEAD=P1;
else {ph->next=p1;
Ph=pe;
ph->next=p2; PE=P2;
} P1=P2;
if (p2) p2=p2->next;
if (p3) p3=p3->next;
return head;
}
}; Blog.csdn.net/havenoidea
Table of Contents