LeetCode(6)

来源:互联网 发布:淘宝客订单部分退款 编辑:程序博客网 时间:2024/06/05 20:43

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,所以我们可以用遍历的方法。

  1. 当当前的head满足k的条件时,将head的第k个next作为输入,进行下一次求解。
  2. 当当前head不满足k的条件时,则直接返回head。
  3. 在获得某次递归的返回后,则单独进行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;}


0 0