from : https://leetcode.com/problems/reverse-nodes-in-k-group/
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
Solution 1:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head) {
ListNode *last = head->next, *p=last->next;
while(p) {
last->next = p->next;
p->next = head->next;
head->next = p;
p = last->next;
}
return last;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(k <= 1 || !head) return head;
ListNode* ph = new ListNode(0);
ph->next = head;
ListNode *p=ph, *q=ph;
while(true) {
int n = k;
while(n-- && q) {
q = q->next;
}
if(!q) break;
ListNode *t = q->next;
q->next = NULL;
q = reverse(p);
q->next = t;
p = q;
}
p = ph->next;
delete ph;
return p;
}
};
本文介绍如何在给定的链表中反转K个一组的节点,详细解释了算法实现,并提供了示例代码。
3229

被折叠的 条评论
为什么被折叠?



