题意
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked 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
解法
- 记录已完成交换段的尾节点
- 记录待交换段的尾节点
实现
/**
* 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) return head;
ListNode* cur = head;
ListNode* pre = NULL;
while(cur != NULL){
int idx = 1;
while(idx < k && cur != NULL){
++idx;
cur = cur->next;
}
if(idx <= k && cur == NULL) break; //注意点
ListNode* cnext = cur->next;//注意点
ListNode* scur = head;
if(pre != NULL) scur = pre->next;
while(scur->next != cnext){
ListNode* next = scur->next;
scur->next = next->next;
if(pre == NULL){
next->next = head;
head = next;
}else{
next->next = pre->next;
pre->next = next;
}
}
pre = scur;
cur = scur->next;
}
return head;
}
};
本文介绍了一种链表操作的方法,即按K个一组进行反转。这种方法不仅保持了链表中剩余节点的原始顺序,还详细说明了如何通过记录已完成交换段的尾节点和待交换段的尾节点来实现这一过程。
931

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



