您的位置:首页 > Web前端 > Node.js

LeetCode(6) - Reverse Nodes in k-Group

2017-04-11 00:15 381 查看
https://leetcode.com/problems/reverse-nodes-in-k-group/#/description

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


Solution:

本题的重点在于每k个数进行reverse,所以我们可以用遍历的方法。

当当前的head满足k的条件时,将head的第k个next作为输入,进行下一次求解。
当当前head不满足k的条件时,则直接返回head。
在获得某次递归的返回后,则单独进行k的reverse。
代码如下:

public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

public ListNode reverseKGroup(ListNode head, int k) {
int count = k;
ListNode next = head;
//检测剩余的ListNode数
do {
if(next != null) {
next = next.next;
} else {
break;
}
} while (--count > 0);

if(count == 0) {
next = reverseKGroup(next, k);

while (count++ < k) {
//从前往后交换位置
ListNode temp = head.next;
head.next = next;
next = head;
head = temp;
}

head = next;
}

return  head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: