Hard程度题
题目:
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
为之前的题目Swap Nodes In Pairs两个两个交换的更一般情况,有了这题的基础,这里只要稍加改进即可,每次改造节点后都判断余下的节点数是否小于K
AC解
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
int a = k;
ListNode *temp = head;//temp用来侦测后面节点是否大于等于K
while (temp != nullptr)
{
temp = temp->next;
a--;
}
if (a > 0 || k == 1)//如果节点个数少于K或者K == 1时直接返回
return head;
ListNode dummy(-1);
dummy.next = head;
ListNode *p = &dummy,*prev = head,*cur = head->next,*head2 = head;
while (true)
{
for (int i = k ; i > 1; i--)
{//改造节点
head2->next = cur->next;
cur->next = prev;
prev = cur;
cur = head2->next;
}
p->next = prev;//第一次执行时,将返回链表的头结点存入dummy.next,后面执行时将两段链表连接起来
p = head2;//p用来存储当前的head2头结点,当接下来的K个节点改造完毕后
head2 = cur;//head2指向剩余未改造的链表头
//侦测后面节点是否大于等于K
a = k;
temp = head2;
while (temp)
{
temp = temp->next;
a--;
}
if (a > 0)
return dummy.next;//如果节点数小于K返回
//将prev cur赋值 准备开始下次改造节点
prev = head2;
cur = prev->next;
}
}
};
代码可读性差,参照别人解法,思想一致,但代码更优美
AC解
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
if (head == nullptr || head->next == nullptr || k < 2)
return head;
ListNode dummy(-1);
dummy.next = head;
for (ListNode *prev = &dummy,*end = head; end; end = prev->next)
{
for (int i = 1; i < k && end; i++)
end = end->next;
if (end == nullptr)//不足K个
break;
prev = reverse(prev,prev->next,end);
}
return dummy.next;
}
//prev是begin前的一个节点
//返回反转后的最后一个节点,用于连接连续两个反转的链表
ListNode *reverse(ListNode *prev,ListNode *begin,ListNode *end)
{
ListNode *end_next = end->next;
for (ListNode *p = begin,*cur = p->next,*next = cur->next;
cur != end_next;
p = cur,cur = next,next = next ? next->next:nullptr)
cur->next = p;
begin->next = end_next;
prev->next = end;
return begin;
}
};