Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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的倍数,那么你需要将余下的结点保留在末尾;
- 你不能改变结点中的值,你只能改动结点的位置。
对于这道题,我已尽我所能却没有一丝的想法,后面去参考了别人的博客,看了别人的想法才明白。心里面不禁暗自的“夸奖”自己,原来我在算法这块儿这么“强”。这道题主要可以用递归的思想去做,然后采用头插法逆序建表。不了解头插法建表的童鞋可以先去了解一下,之后再来做这道题目。下面附上改进后的代码:
public class Solution
{
public ListNode reverseKGroup(ListNode head, int k)
{
if(head == null)
return head;
if(head.next == null)
return head;
ListNode cur = head;
int count = 0;
while(cur != null && count != k)
{
cur = cur.next;
count++;
}
if(count == k)
{
cur = reverseKGroup(cur, k);
/*
* 使用头插法建立逆序链表
*/
while(--count >= 0)
{
ListNode tmp = head.next;
head.next = cur;
cur = head;
head = tmp;
}
head = cur;
}
return head;
}
}
欢迎各位童鞋指出新的想法,我也可以学习学习各位大神的解答。附上执行结果,第一次遇见这样的执行效果,心里美滋滋的。哈哈!