题目源自于leetcode。
题目:Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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个链表逆序。然后对整个链表遍历时顺序调用多次该函数。
注意细节:
1、逆序部分的开头之前和结尾之后如何接上。
2、在某次逆序之后,如何找到下一次逆序时逆序部分的开头之前、结尾之后。
3、函数最后要返回新链表的首结点。
4、访问结构体的成员,指针可以使用->,对象则要用.
代码:
/**
* 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(k<=1)
return head;
struct ListNode H(0);
H.next = head;
ListNode *left, *right;
ListNode *tmp;
left = &H;
right = head;
int num = 0;
while(right != NULL)
{
num++;
if(num == k)
{
tmp = left->next;
reverse(left, right->next, k);
num = 0;
left = tmp;
right = left->next;
}
else
{
right = right->next;
}
}
return H.next;
}
//逆序段的前一个结点为pre,逆序段的后一个结点为end
void reverse(ListNode *pre, ListNode *end, int n)
{
ListNode *oldl, *newl;
oldl = pre->next->next;
pre->next->next = end;
for(int i=1;i<n;i++)
{
newl = oldl;
oldl = oldl->next;
newl->next = pre->next;
pre->next = newl;
}
}
};