1.题目
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 list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Example 3:
Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]
Example 4:
Input: head = [1], k = 1
Output: [1]
2. 链表性质
/* 基本的单链表节点 */
class ListNode {
int val;
ListNode next;
}
void traverse(ListNode head) {
for (ListNode p = head; p != null; p = p.next) {
// 迭代访问 p.val
}
}
void traverse(ListNode head) {
// 递归访问 head.val
traverse(head.next);
}
3.代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
/** 反转区间 [a, b) !!!!!的元素,注意是左闭右闭 */
ListNode* reverse(ListNode* start,ListNode* end)
{
ListNode* pre;
ListNode* cur;
ListNode* nex;
pre=NULL;
cur=start;
nex=cur;
//这里不能判断end->next,因为可能出现空指针
while(cur!=end)
{
//nex赋值必须放在最前,否则会出现NUll->NEXT情况
nex=cur->next;
cur->next=pre;
cout<<cur->val<<"kkkk";
//交换指针
pre=cur;
cur=nex;
}
cout<<"wwwwww";
//注意这里返回的是pre,因为cur已经提前交换到开区间b的位置了
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k)
{
//该题采用迭代
ListNode *save;
ListNode* keep=head;
ListNode* keep2=head;
//这里应执行k次,对应[a,b)区间
for(int j=0;j<k;j++)
{
if(keep2==NULL)
{
return head;
}
keep2=keep2->next;
}
save=reverse(keep,keep2);
keep->next=reverseKGroup(keep2,k);
return save;
}
};
链接: link.