题目: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
Subscribe to see which companies asked this question.
解析:
题目的意思是将链表进行部分逆置,逆置的部分跟K值有关,如上所示, 对于 1->2->3->4->5 当k=2时 2->1->4->3->5
当k=3时 3->2->1->4->5
后面 4 5没变是因为做完一次 3 2 1 剩下的 4 5 已经比k小了,所以保持原来的顺序
主要考虑有两点:
1)链表逻辑转换的调用和操作
2)不要存在悬浮指针和断开链接
代码:
class
Solution {
public
:
ListNode *reverseKGroup(ListNode *head,
int
k) {
ListNode *p=head,*q,*reverhead;
int
temp=
0
;
int
t;
while
(p)
{
++temp;
p=p->next;
}
if
(temp==
0
||
1
==k||k>temp)
return
head;
ListNode *result=
new
ListNode(
0
);
//创建头结点 并用reverhead保存头结点
result->next=head;
reverhead=result;
p=result->next;
//用p来指向下一个节点,进行操作的第一个有效节点
while
(k<=temp)
//外层循环用k和temp
{
t=k;
//里层循环每次操作t个
ListNode *remark=p;
//用remark保存每次进行部分逆置的第一个节点,该节点将指向部分逆置的下一个节点,如上k=2时,1指向3
while
(t>
0
)
//将p开始的t个节点进行逆置
{
q=p;
p=p->next;
q->next=result->next;
result->next=q;
t--;
}
remark->next=p;
//将每部分连接起来
result=remark;
//改变result,指向部分逆置的最后一个节点
temp=temp-k;
//做了部分逆置后,改变temp
}
return
reverhead->next;
}
};