Reverse Nodes in k-Group

Reverse Nodes in k-Group

问题:

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

思路:

  很简单的翻转链表而已,把图画明白了就可以了。

我的代码:

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        int n = 0;
        while(head != null)
        {
            head = head.next;
            n++;
        }
        if(n < k) return dummy.next;
        ListNode pre = dummy;
        ListNode curpre = dummy.next;
        ListNode cur = curpre.next;
        for(int i = 0; i < n/k; i++)
        {
            for(int cnt = 1; cnt < k; cnt++)
            {
                ListNode next = cur.next;
                curpre.next = cur.next;
                cur.next = pre.next;
                pre.next = cur;
                cur = next;
            }
            pre = curpre;
            curpre = curpre.next;
            if(curpre != null)
                cur = curpre.next;
        }
        return dummy.next;
    }
}
View Code
原文地址:https://www.cnblogs.com/sunshisonghit/p/4350755.html