原题:
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
对于给定的一个链表,把该链表中每前k个节点的排序反转。(+特殊情况)
第一次基本思路:
就是很简单的,每次取出前几个k值,进行反转,对剩下的链表进行递归处理。
下面给出代码:
第一版ac:
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
struct ListNode* p;
if(head==NULL||k==1)
return head;
int num=0;
p=head;
for(;p!=NULL;p=p->next)
{
num++;
}
if(num<k)
return head;
struct ListNode *p1;
struct ListNode *p2;
struct ListNode *p3;
struct ListNode *nexthead;
struct ListNode *result;
p1=head;
p2=head->next;
p3=p2->next;
for(int n=0;n<k-1;n++)
{
p2->next=p1;
p1=p2;
p2=p3;
if(p3!=NULL)
{
p3=p3->next;
}
}
nexthead=p2;
result=reverseKGroup(nexthead,k);
head->next=result;
return p1;
}
可以看到ac以后的效率情况。
可以看到效率真的不是太好。(已经快到谷底了,13ms)
现在对代码本身进行手动优化,也就是保留原来的算法。
等我优化下。。。
进行了小优化,等我用源代码再次进行提交的时候(就是第一次的代码没有变动),竟然变成了一次6ms,一次9m。看来leetcode的服务器不是很靠谱啊。
这种想法还是不错的,看了leetcode的代码,一种是用递归,一种没有用,没有用的那种看了一下还可以进行一下优化。在基本的NULL的判断上。
没有用的就是一步一步的反转了,加了很多的过程控制,其实也还不错,相比较的话,我觉得写的好的应该比递归的性能可能会好一些,毕竟处理递归是一个比较慢速的过程。
也不知道说的对不对。