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

25. Reverse Nodes in k-Group

2016-02-29 14:59 603 查看

Reverse Nodes in k-Group

  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

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode shao = head;
int count = 0;
while(shao != null && count != k){  //寻找k+1个节点
shao = shao.next;
count++;
}
if(count == k){
shao = reverseKGroup(shao,k);  //使k+1的节点作为shao的头节点
while(count-- > 0){  //需翻转的次数
ListNode tmp = head.next;
head.next = shao;
shao = head;
head = tmp;
}
head = shao;
}
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: