25. Reverse Nodes in k-Group

来源:互联网 发布:淘宝客推广开通条件 编辑:程序博客网 时间:2024/06/05 17:59

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;    }}
0 0